Insert lines in a file starting from a specific line

后端 未结 4 713
生来不讨喜
生来不讨喜 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:38

    Or anoter one example with the sed:

    echo -e "line 1\nline 2\nline 3\nline 4" > /tmp/test.py
    cat /tmp/test.py
    line 1
    line 2
    line 3
    line 4
    
    sed -i '2 a line 2.5' /tmp/test.py    # sed for inside of the file 'LINE_NUMBER append TEXT'
    cat /tmp/test.py
    line 1
    line 2
    line 2.5
    line 3
    line 4
    
    0 讨论(0)
  • 2020-12-23 02:42

    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.
    $ 
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-12-23 02:56

    sed is your friend:

    :~$ cat text.txt 
    foo
    bar
    baz
    ~$ 
    
    ~$ sed '/^bar/\na this is the new line/' text.txt > new_text.txt
    ~$ cat new_text.txt 
    foo
    bar
    this is the new line
    baz
    ~$ 
    
    0 讨论(0)
提交回复
热议问题