Bash: Inserting one file's content into another file after the pattern

后端 未结 5 1500
一向
一向 2020-12-30 07:16

I\'m trying to write a bash script, which will do the following:

  1. reads the content from the first file (as a first argument)
  2. reads the content from th
5条回答
  •  旧时难觅i
    2020-12-30 07:56

    Using awk works as well.

    To insert before the ###marker### line :

    // for each  of second_file.txt :
    //   if  matches regexp ###marker###, outputs first_file.txt.
    //   **without any condition :** print 
    awk '/###marker###/ { system ( "cat first_file.txt" ) } \
         { print; } \' second_file.txt
    

    To insert after the ###marker###line :

    // for each  of second_file.txt :
    //   **without any condition :** print 
    //   if  matches regexp ###marker###, outputs first_file.txt.
    awk '{ print; } \
         /###marker###/ { system ( "cat first_file.txt" ) } \' second_file.txt
    

    To replace the ###marker### line :

    // for each  of second_file.txt :
    //   if  matches regexp ###marker###, outputs first_file.txt.
    //   **else**, print 
    awk '/###marker###/ { system ( "cat first_file.txt" ) } \
         !/###marker###/ { print; }' second_file.txt
    

    If you want to do in-place replacement, use a temp file for being sure the pipe doesn't start before awk has read the entire file; add :

    > second_file.txt.new
    mv second_file.txt{.new,}
    // (like "mv second_file.txt.new second_file.txt", but shorter to type !)
    

    If you want replacement inside of the line, (replacing just the pattern and keeping the rest of the line), a similar solution should be achievable with sed instead of awk.

提交回复
热议问题