How to insert a string into a specific string in multiple files on Unix?

I need to insert a line with special text into the second line (thus moving other lines in the file) from hundreds of files in the directory. Any quick Unix tips on how to do this?

+6
unix perl sed
source share
4 answers
sed -i -e '2iYour line here' /dir/* 

Note that the semantics of sed -i depend on the taste of Unix, so check out man sed . It is written for the taste of GNU.

+13
source share
 perl -pi -we'print "extra line\n" if $. == 3; close ARGV if eof' files 

close(ARGV) you need to restart the line counter $. at the beginning of each file; by default, it counts lines between files.

+2
source share

this is AWK , not 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 
+1
source share
 ls | xargs --replace=foo perl -i -ne 'print; print "second line text\n" unless $x++;' foo 
0
source share

All Articles