Insert lines in a file starting from a specific line

后端 未结 4 736
生来不讨喜
生来不讨喜 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条回答
  •  旧时难觅i
    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.
    $ 
    

提交回复
热议问题