tags:

views:

329

answers:

4

I need to insert a line with specific text on the second line (thus moving the other lines down in the file) of hundreds of files in a directory. Any quick Unix tips on how that can be done?

+10  A: 
sed -i -e '2iYour line here' /dir/*

Note that sed -i semantics vary by Unix flavor, so check your man sed. This is written for the GNU flavor.

chaos
wow .. almost makes me want to learn sed. Thanks a bunch!
Learning
+1  A: 

this is an AWK use rather than the sed,

for i in $(<list_of_files)
do
     awk '{if (FNR!=2) print $0; 
           else { print "new line"; print $0}}' $i > ${i}.tmp;
     mv ${i}.tmp $i;
done
nik
A: 
ls | xargs --replace=foo perl -i -ne 'print; print "second line text\n" unless $x++;' foo
I vote *never* to recommend `perl -i` without a backup: `perl -i.bak`. It's easy, and you can easily remove the backups once you're sure you didn't get your edit wrong.
Telemachus
+2  A: 
perl -pi -we'print "extra line\n" if $. == 3; close ARGV if eof' files

The close(ARGV) is necessary to restart the line counter $. at the beginning of each file; by default, it counts lines across files.

ysth
Don't you think it's worth doing `-i.bak` to protect you from a typo wiping out quite a lot of data? (Just imagine you forget `-p`.)
Telemachus
@Telemachus: when doing a whole directory, I prefer to copy the whole directory first (e.g. cp -a dir{,.save}); then I can mv it back if needed.
ysth