Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

find awk - add line to files?

Options
  • 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 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 Posts: 6,508 ✭✭✭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 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 Posts: 730 ✭✭✭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