bashsed

Insert lines in a file starting from a specific line


I would like to insert lines into a file in bash starting from a specific line.

Each line is a string which is an element of an array

line[0]="foo"
line[1]="bar"
...

and the specific line is 'fields'

file="$(cat $myfile)"
for p in $file; do
    if [ "$p" = 'fields' ]
        then insertlines()     #<- here
    fi
done

Solution

  • 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
    

    Note: Option -i is not supported on all versions of sed (e.g. not on Solaris). You can use GNU sed, which does support it.