Insert lines in a file starting from a specific line

后端 未结 4 759
生来不讨喜
生来不讨喜 2020-12-23 01:54

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\"         


        
4条回答
  •  被撕碎了的回忆
    2020-12-23 02:55

    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
    

提交回复
热议问题