Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.
Hi all, please see this major site announcement: https://www.boards.ie/discussion/2058427594/boards-ie-2026

find awk - add line to files?

  • 17-10-2006 10:57AM
    #1
    Closed Accounts Posts: 247 ✭✭


    Hi,

    I have numerous files that i want to add a line to.

    I can do this using:
    find . -name "runme.sh" | xargs awk 'BEGIN {print "setenv whatever"} {print $0};'
    

    But this will only print to std_out. I want to print this directly back into the same file. How can i do this?
    Thanks
    John

    As an added extra i would like to add the "setenv whatever" after the first line of every file. So instead of 'BEGIN i should use????

    Thanks again


Comments

  • Registered Users, Registered Users 2 Posts: 2,082 ✭✭✭Tobias Greeshman


    To add at the end of a file append the ">>" character to print to the end of a file.

    As for the "setenv..." well IIR awk sees data from input files as records and fields and you can modify them as they come in. With this in mind it should be pretty straight forward to redirect the modified output back to file. Use ">" so it will overwrite the old file though.

    The Manual for awk is here


  • Registered Users, Registered Users 2 Posts: 6,753 ✭✭✭daymobrew


    I'm not too familar with xargs so I use 'for' loops. This code worked for me.
    for f in `find . -name "runme.sh"`
    do
      # NR means record/line number. Direct output to temp file.
      awk 'NR == 2 {print "setenv whatever"} {print}' $f > $f.$$
      # Rename the temp file, overwriting the original file.
      mv $f.$$ $f
      # Display something to show progress.
      echo "$f - done"
    done
    
    Input file:
    Line 1
    2nd line
    Third line
    
    became
    Line 1
    setenv whatever
    2nd line
    Third line
    


  • Registered Users, Registered Users 2 Posts: 1,865 ✭✭✭Syth


    silas wrote:
    Use ">" so it will overwrite the old file though.
    Using > will not work. Files are read in in streams, so it'll start overwritting the original file before it's finished reading it, so you'll loose data. Your best bet is to use a temporary file. Look into 'mktemp' to generate a temporary file.


  • Registered Users, Registered Users 2, Paid Member Posts: 749 ✭✭✭Dero


    Would sed not be a better tool for this? Especially with gnu sed as it can change files in place with the -i flag. 2i will insert at the 2nd line of the input file.
    sed -i '2i setenv whatever' runme.sh
    

    If your sed doesn't have -i:
    sed '2i setenv whatever' runme.sh > tmpfile; mv tmpfile runme.sh
    


    Edit: Didn't notice the 2nd line requirement.


Advertisement
Advertisement