Results 1 to 4 of 4
  1. #1
    Join Date
    Apr 2007
    Posts
    2

    Cool Unanswered: how to add line at bottom of file in linux

    please tell me how to add line at bottom of file in linux by using a sed or awk ?
    is a script for the same ?

  2. #2
    Join Date
    Jan 2007
    Location
    Jena, Germany
    Posts
    2,721
    Code:
    echo "line" >> file
    I'm sure awk can do that as well (for example in the END block), but why make it more complicated?
    Knut Stolze
    IBM DB2 Analytics Accelerator
    IBM Germany Research & Development

  3. #3
    Join Date
    Aug 2006
    Location
    The Netherlands
    Posts
    248
    Hi,

    I understood your question differently then Knut did and think something like this is what you're looking for.
    Like Knut mentioned, here's an 'awk' example. The advantage is that first the complete file is read into memory and after that the memory content is written to the file on disk again (including the extra last line). With this you can overwrite the original file in one step because awk has finished reading the input filestream before the output filestream is created. (Offcourse this only works if there's enough memory available to store the complete file.)
    Something that's going terribly wrong with 'sed', where you allways have to store the output in a helpfile first and overwrite the original with that.
    Awk solution:
    Code:
    #!/bin/bash                             
                                            
    awk '   {   line[NR] = $0   }           
        END {                               
                for(i = 1; i <= NR; i++)    
                    print line[i] > FILENAME
                print "" > FILENAME         
            }' $1
    Sed solution:
    Code:
    #!/bin/bash       
                      
    sed '$s/$/\       
    /' $1 > "${1}.tmp"
    mv "${1}.tmp" $1
    Regards
    Last edited by Tyveleyn; 04-21-07 at 07:51.

  4. #4
    Join Date
    Jan 2007
    Location
    Jena, Germany
    Posts
    2,721
    Yeah, it really depends on what you want to do. Reading the entire file into main memory just to add a line at the end and leaving the rest of the file untouched would be overkill and a huge waste of resources, of course. Even if you need to modify the file, I would still recommend to not rely on main-memory. Only for really small (just a few MB) files, this is acceptable.
    Knut Stolze
    IBM DB2 Analytics Accelerator
    IBM Germany Research & Development

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •