insert lines with sed
April 13, 2010 | by rob @ 12:16 pm | comments (1) | filed under [unix]

On occasion, I need to bulk insert text at specific locations in certain files. Sometimes at a line number. More often at a location matching a pattern. Let’s say you had an original file:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
text text text 
 
keyword
 
text text text 
text text text 
text text text 
text text text 
text text text 
text text text 
text text text 
 
insert below
 
text text text 
text text text 
text text text 
text text text 
text text text 
text text text

and you needed to insert text from file “ins.txt” at the location “insert below”. All you need to do is run this series of commands:

1
find . -name "*.txt" -exec grep -l keyword {} \; | xargs sed -i '/insert below/r ins.txt'

Basically this command interprets as:

1. in the current directory, find all the files with extension “txt”
2. from those files, find only the ones containing the phrase “keyword”
2. insert the text from “ins.txt” below the phrase “insert below” in those matching files

Of course regular expressions work across the board for this type of operation, with both the “find” and “grep” portions.