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?
The simplest way to append multiple lines to a file is to use the echo and printf command. Let us start with echo. Echo is a command used to output a string or multiple strings as arguments. Echo is available in all Linux distributions, making it a good tool for redirecting output to a file.
There are different ways to insert a new line in a file using sed, such as using the “a” command, the “i” command, or the substitution command, “s“. sed's “a” command and “i” command are pretty similar.
You can use cat with redirection to append a file to another file. You do this by using the append redirection symbol, ``>>''. To append one file to the end of another, type cat, the file you want to append, then >>, then the file you want to append to, and press <Enter>.
Type vi * to edit all the files in a directory, though this will give you an error in some Unix systems. Type CTRL-g or :f to get the name of your current file; :args lists all filenames from the command line and puts brackets around the [current] file.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With