Insert lines in a file starting from a specific line

This is definitely a case where you want to use something like sed (or awk or perl) rather than readling one line at a time in a shell loop. This is not the sort of thing the shell does well or efficiently.

You might find it handy to write a reusable function. Here's a simple one, though it won't work on fully-arbitrary text (slashes or regular expression metacharacters will confuse things):

function insertAfter # file line newText
{
   local file="$1" line="$2" newText="$3"
   sed -i -e "/^$line$/a"$'\\\n'"$newText"$'\n' "$file"
}

Example:

$ cat foo.txt
Now is the time for all good men to come to the aid of their party.
The quick brown fox jumps over a lazy dog.
$ insertAfter foo.txt \
   "Now is the time for all good men to come to the aid of their party." \
   "The previous line is missing 'bjkquvxz.'"
$ cat foo.txt
Now is the time for all good men to come to the aid of their party.
The previous line is missing 'bjkquvxz.'
The quick brown fox jumps over a lazy dog.
$ 

Or anoter one example with the sed:

Prepare a test.txt file:

echo -e "line 1\nline 2\nline 3\nline 4" > /tmp/test.txt

cat /tmp/test.txt
line 1
line 2
line 3
line 4

Add a new line into the test.txt file:

sed -i '2 a line 2.5' /tmp/test.txt
# sed for in-place editing (-i) of the file: 'LINE_NUMBER a-ppend TEXT_TO_ADD'

cat /tmp/test.txt
line 1
line 2
line 2.5
line 3
line 4

This can be done with sed: sed 's/fields/fields\nNew Inserted Line/'

$ cat file.txt 
line 1
line 2 
fields
line 3
another line 
fields
dkhs

$ sed 's/fields/fields\nNew Inserted Line/' file.txt 
line 1
line 2 
fields
New Inserted Line
line 3
another line 
fields
New Inserted Line
dkhs

Use -i to save in-place instead of printing to stdout

sed -i 's/fields/fields\nNew Inserted Line/'

As a bash script:

#!/bin/bash

match='fields'
insert='New Inserted Line'
file='file.txt'

sed -i "s/$match/$match\n$insert/" $file

Tags:

Bash

Sed