Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I insert a line at a specific row in multiple files on Unix?

Tags:

unix

sed

perl

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?

like image 784
Learning Avatar asked Aug 05 '09 12:08

Learning


People also ask

How do I add a line to multiple files in Unix?

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.

How do you add a line in Unix?

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.

How do I add a line from one file to another in Linux?

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>.

How do you edit multiple files in Unix?

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.


2 Answers

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.

like image 119
chaos Avatar answered Sep 22 '22 14:09

chaos


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.

like image 40
ysth Avatar answered Sep 20 '22 14:09

ysth