Insert multiple lines into a file after specified pattern using shell script












58















I want to insert multiple lines into a file using shell script.
Let us consider my input file contents are:
input.txt:



abcd
accd
cdef
line
web


Now I have to insert four lines after the line 'cdef' in the input.txt file.
After inserting my file should change like this:



abcd
accd
cdef
line1
line2
line3
line4
line
web


The above insertion I should do using the shell script. Can any one help me?










share|improve this question





























    58















    I want to insert multiple lines into a file using shell script.
    Let us consider my input file contents are:
    input.txt:



    abcd
    accd
    cdef
    line
    web


    Now I have to insert four lines after the line 'cdef' in the input.txt file.
    After inserting my file should change like this:



    abcd
    accd
    cdef
    line1
    line2
    line3
    line4
    line
    web


    The above insertion I should do using the shell script. Can any one help me?










    share|improve this question



























      58












      58








      58


      14






      I want to insert multiple lines into a file using shell script.
      Let us consider my input file contents are:
      input.txt:



      abcd
      accd
      cdef
      line
      web


      Now I have to insert four lines after the line 'cdef' in the input.txt file.
      After inserting my file should change like this:



      abcd
      accd
      cdef
      line1
      line2
      line3
      line4
      line
      web


      The above insertion I should do using the shell script. Can any one help me?










      share|improve this question
















      I want to insert multiple lines into a file using shell script.
      Let us consider my input file contents are:
      input.txt:



      abcd
      accd
      cdef
      line
      web


      Now I have to insert four lines after the line 'cdef' in the input.txt file.
      After inserting my file should change like this:



      abcd
      accd
      cdef
      line1
      line2
      line3
      line4
      line
      web


      The above insertion I should do using the shell script. Can any one help me?







      linux bash shell sed awk






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 29 '17 at 10:57









      smarber

      2,54641845




      2,54641845










      asked Mar 19 '14 at 5:43









      user27user27

      5073713




      5073713
























          7 Answers
          7






          active

          oldest

          votes


















          79














          Another sed,



          sed '/cdef/r add.txt' input.txt


          input.txt:



          abcd
          accd
          cdef
          line
          web


          add.txt:



          line1
          line2
          line3
          line4


          Test:



          sat:~# sed '/cdef/r add.txt' input.txt
          abcd
          accd
          cdef
          line1
          line2
          line3
          line4
          line
          web


          If you want to apply the changes in input.txt file. Then, use -i with sed.



          sed -i '/cdef/r add.txt' input.txt


          If you want to use a regex as an expression you have to use the -E tag with sed.



          sed -E '/RegexPattern/r add.txt' input.txt





          share|improve this answer


























          • Is there a way to do this the other way around (remove text found in add.txt from input.txt) ?

            – Sina
            Sep 14 '14 at 0:20











          • A variation, that allows for an anonymous file is to pipe a here document into a sed invocation and use the r command to read from /dev/stdin.

            – potong
            Aug 2 '18 at 14:19



















          29














          Using GNU sed:



          sed "/cdef/aline1nline2nline3nline4" input.txt


          If you started with:



          abcd
          accd
          cdef
          line
          web


          this would produce:



          abcd
          accd
          cdef
          line1
          line2
          line3
          line4
          line
          web


          If you want to save the changes to the file in-place, say:



          sed -i "/cdef/aline1nline2nline3nline4" input.txt





          share|improve this answer



















          • 3





            I am new to sed but wow I am in love with its power! If you want to append an empty newline first you have to escape the backslash character after the append command like this : sed "/cdef/a\nline1nline2nline3nline4" input.txt. I am not sure why it works like that though, if somebody could explain this would be nice!

            – hdl
            Sep 23 '15 at 13:20






          • 1





            The current command inserts the line* on every mention of cdef, is there a way to make it so that it only inserts on the first time it encounters cdef and no more?

            – CMCDragonkai
            Oct 20 '15 at 13:32






          • 1





            MacOS sed doesn't implement the a command precisely the same as GNU sed, so the above won't work in MacOS without mods - at least as of macOS 10.13 ( see unix.stackexchange.com/a/131940/230763 )

            – Mike Lutz
            Jul 13 '18 at 22:19





















          13














          Using awk:



          awk '/cdef/{print $0 RS "line1" RS "line2" RS "line3" RS "line4";next}1' input.txt 


          Explanation:




          • You find the line you want to insert from using /.../

          • You print the current line using print $0


          • RS is built-in awk variable that is by default set to new-line.

          • You add new lines separated by this variable


          • 1 at the end results in printing of every other lines. Using next before it allows us to prevent the current line since you have already printed it using print $0.





          $ awk '/cdef/{print $0 RS "line1" RS "line2" RS "line3" RS "line4";next}1' input.txt
          abcd
          accd
          cdef
          line1
          line2
          line3
          line4
          line
          web





          To make changes to the file you can do:



          awk '...' input.txt > tmp && mv tmp input.txt





          share|improve this answer































            13














            sed '/^cdef$/r'<(
            echo "line1"
            echo "line2"
            echo "line3"
            echo "line4"
            ) -i -- input.txt





            share|improve this answer
























            • works nicely and makes it much more readable

              – KoZm0kNoT
              Aug 23 '18 at 16:26













            • Missed this good answer. Shorter but less readable is sed '/^cdef$/r' <(printf "%sn" line{1..4}) -i -- input.txt.

              – Walter A
              Jan 2 at 10:40



















            1














            This answer is easy to understand




            • Copy before the pattern

            • Add your lines

            • Copy after the pattern


            • Replace original file



              FILENAME='app/Providers/AuthServiceProvider.php'




            STEP 1 copy until the pattern



            sed '/THEPATTERNYOUARELOOKINGFOR/Q' $FILENAME >>${FILENAME}_temp


            STEP 2 add your lines



            cat << 'EOL' >> ${FILENAME}_temp

            HERE YOU COPY AND
            PASTE MULTIPLE
            LINES, ALSO YOU CAN
            //WRITE COMMENTS

            AND NEW LINES
            AND SPECIAL CHARS LIKE $THISONE

            EOL


            STEP 3 add the rest of the file



            grep -A 9999 'THEPATTERNYOUARELOOKINGFOR' $FILENAME >>${FILENAME}_temp


            REPLACE original file



            mv ${FILENAME}_temp $FILENAME


            if you need variables, in step 2 replace 'EOL' with EOL



            cat << EOL >> ${FILENAME}_temp

            this variable will expand: $variable1

            EOL





            share|improve this answer































              0














              I needed to template a few files with minimal tooling and for me the issue with above sed -e '/../r file.txt is that it only appends the file after it prints out the rest of the match, it doesn't replace it.



              This doesn't do it (all matches are replaced and pattern matching continues from same point)



              #!/bin/bash

              TEMPDIR=$(mktemp -d "${TMPDIR:-/tmp/}$(basename $0).XXXXXXXXXXXX")
              # remove on exit
              trap "rm -rf $TEMPDIR" EXIT

              DCTEMPLATE=$TEMPDIR/dctemplate.txt
              DCTEMPFILE=$TEMPDIR/dctempfile.txt

              # template that will replace
              printf "0replacement
              1${SHELL} data
              2anotherlinenoEOL" > $DCTEMPLATE

              # test data
              echo -e "xxy n987 nxx xxn yz yxxyy" > $DCTEMPFILE

              # print original for debug
              echo "---8<--- $DCTEMPFILE"
              cat $DCTEMPFILE
              echo "---8<--- $DCTEMPLATE"
              cat $DCTEMPLATE
              echo "---8<---"

              # replace 'xx' -> contents of $DCTEMPFILE
              perl -e "our $fname = '${DCTEMPLATE}';" -pe 's/xx/`cat $fname`/eg' ${DCTEMPFILE}





              share|improve this answer































                0














                You can use awk for inserting output of some command in the middle of input.txt.

                The lines to be inserted can be the output of a cat otherfile, ls -l or 4 lines with a number generated by printf.



                awk 'NR==FNR {a[NR]=$0;next}
                {print}
                /cdef/ {for (i=1; i <= length(a); i++) { print a[i] }}'
                <(printf "%sn" line{1..4}) input.txt





                share|improve this answer

























                  Your Answer






                  StackExchange.ifUsing("editor", function () {
                  StackExchange.using("externalEditor", function () {
                  StackExchange.using("snippets", function () {
                  StackExchange.snippets.init();
                  });
                  });
                  }, "code-snippets");

                  StackExchange.ready(function() {
                  var channelOptions = {
                  tags: "".split(" "),
                  id: "1"
                  };
                  initTagRenderer("".split(" "), "".split(" "), channelOptions);

                  StackExchange.using("externalEditor", function() {
                  // Have to fire editor after snippets, if snippets enabled
                  if (StackExchange.settings.snippets.snippetsEnabled) {
                  StackExchange.using("snippets", function() {
                  createEditor();
                  });
                  }
                  else {
                  createEditor();
                  }
                  });

                  function createEditor() {
                  StackExchange.prepareEditor({
                  heartbeatType: 'answer',
                  autoActivateHeartbeat: false,
                  convertImagesToLinks: true,
                  noModals: true,
                  showLowRepImageUploadWarning: true,
                  reputationToPostImages: 10,
                  bindNavPrevention: true,
                  postfix: "",
                  imageUploader: {
                  brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                  contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                  allowUrls: true
                  },
                  onDemand: true,
                  discardSelector: ".discard-answer"
                  ,immediatelyShowMarkdownHelp:true
                  });


                  }
                  });














                  draft saved

                  draft discarded


















                  StackExchange.ready(
                  function () {
                  StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f22497246%2finsert-multiple-lines-into-a-file-after-specified-pattern-using-shell-script%23new-answer', 'question_page');
                  }
                  );

                  Post as a guest















                  Required, but never shown

























                  7 Answers
                  7






                  active

                  oldest

                  votes








                  7 Answers
                  7






                  active

                  oldest

                  votes









                  active

                  oldest

                  votes






                  active

                  oldest

                  votes









                  79














                  Another sed,



                  sed '/cdef/r add.txt' input.txt


                  input.txt:



                  abcd
                  accd
                  cdef
                  line
                  web


                  add.txt:



                  line1
                  line2
                  line3
                  line4


                  Test:



                  sat:~# sed '/cdef/r add.txt' input.txt
                  abcd
                  accd
                  cdef
                  line1
                  line2
                  line3
                  line4
                  line
                  web


                  If you want to apply the changes in input.txt file. Then, use -i with sed.



                  sed -i '/cdef/r add.txt' input.txt


                  If you want to use a regex as an expression you have to use the -E tag with sed.



                  sed -E '/RegexPattern/r add.txt' input.txt





                  share|improve this answer


























                  • Is there a way to do this the other way around (remove text found in add.txt from input.txt) ?

                    – Sina
                    Sep 14 '14 at 0:20











                  • A variation, that allows for an anonymous file is to pipe a here document into a sed invocation and use the r command to read from /dev/stdin.

                    – potong
                    Aug 2 '18 at 14:19
















                  79














                  Another sed,



                  sed '/cdef/r add.txt' input.txt


                  input.txt:



                  abcd
                  accd
                  cdef
                  line
                  web


                  add.txt:



                  line1
                  line2
                  line3
                  line4


                  Test:



                  sat:~# sed '/cdef/r add.txt' input.txt
                  abcd
                  accd
                  cdef
                  line1
                  line2
                  line3
                  line4
                  line
                  web


                  If you want to apply the changes in input.txt file. Then, use -i with sed.



                  sed -i '/cdef/r add.txt' input.txt


                  If you want to use a regex as an expression you have to use the -E tag with sed.



                  sed -E '/RegexPattern/r add.txt' input.txt





                  share|improve this answer


























                  • Is there a way to do this the other way around (remove text found in add.txt from input.txt) ?

                    – Sina
                    Sep 14 '14 at 0:20











                  • A variation, that allows for an anonymous file is to pipe a here document into a sed invocation and use the r command to read from /dev/stdin.

                    – potong
                    Aug 2 '18 at 14:19














                  79












                  79








                  79







                  Another sed,



                  sed '/cdef/r add.txt' input.txt


                  input.txt:



                  abcd
                  accd
                  cdef
                  line
                  web


                  add.txt:



                  line1
                  line2
                  line3
                  line4


                  Test:



                  sat:~# sed '/cdef/r add.txt' input.txt
                  abcd
                  accd
                  cdef
                  line1
                  line2
                  line3
                  line4
                  line
                  web


                  If you want to apply the changes in input.txt file. Then, use -i with sed.



                  sed -i '/cdef/r add.txt' input.txt


                  If you want to use a regex as an expression you have to use the -E tag with sed.



                  sed -E '/RegexPattern/r add.txt' input.txt





                  share|improve this answer















                  Another sed,



                  sed '/cdef/r add.txt' input.txt


                  input.txt:



                  abcd
                  accd
                  cdef
                  line
                  web


                  add.txt:



                  line1
                  line2
                  line3
                  line4


                  Test:



                  sat:~# sed '/cdef/r add.txt' input.txt
                  abcd
                  accd
                  cdef
                  line1
                  line2
                  line3
                  line4
                  line
                  web


                  If you want to apply the changes in input.txt file. Then, use -i with sed.



                  sed -i '/cdef/r add.txt' input.txt


                  If you want to use a regex as an expression you have to use the -E tag with sed.



                  sed -E '/RegexPattern/r add.txt' input.txt






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Mar 20 '16 at 14:47









                  yoano

                  5912617




                  5912617










                  answered Mar 19 '14 at 5:58









                  satsat

                  11.8k23056




                  11.8k23056













                  • Is there a way to do this the other way around (remove text found in add.txt from input.txt) ?

                    – Sina
                    Sep 14 '14 at 0:20











                  • A variation, that allows for an anonymous file is to pipe a here document into a sed invocation and use the r command to read from /dev/stdin.

                    – potong
                    Aug 2 '18 at 14:19



















                  • Is there a way to do this the other way around (remove text found in add.txt from input.txt) ?

                    – Sina
                    Sep 14 '14 at 0:20











                  • A variation, that allows for an anonymous file is to pipe a here document into a sed invocation and use the r command to read from /dev/stdin.

                    – potong
                    Aug 2 '18 at 14:19

















                  Is there a way to do this the other way around (remove text found in add.txt from input.txt) ?

                  – Sina
                  Sep 14 '14 at 0:20





                  Is there a way to do this the other way around (remove text found in add.txt from input.txt) ?

                  – Sina
                  Sep 14 '14 at 0:20













                  A variation, that allows for an anonymous file is to pipe a here document into a sed invocation and use the r command to read from /dev/stdin.

                  – potong
                  Aug 2 '18 at 14:19





                  A variation, that allows for an anonymous file is to pipe a here document into a sed invocation and use the r command to read from /dev/stdin.

                  – potong
                  Aug 2 '18 at 14:19













                  29














                  Using GNU sed:



                  sed "/cdef/aline1nline2nline3nline4" input.txt


                  If you started with:



                  abcd
                  accd
                  cdef
                  line
                  web


                  this would produce:



                  abcd
                  accd
                  cdef
                  line1
                  line2
                  line3
                  line4
                  line
                  web


                  If you want to save the changes to the file in-place, say:



                  sed -i "/cdef/aline1nline2nline3nline4" input.txt





                  share|improve this answer



















                  • 3





                    I am new to sed but wow I am in love with its power! If you want to append an empty newline first you have to escape the backslash character after the append command like this : sed "/cdef/a\nline1nline2nline3nline4" input.txt. I am not sure why it works like that though, if somebody could explain this would be nice!

                    – hdl
                    Sep 23 '15 at 13:20






                  • 1





                    The current command inserts the line* on every mention of cdef, is there a way to make it so that it only inserts on the first time it encounters cdef and no more?

                    – CMCDragonkai
                    Oct 20 '15 at 13:32






                  • 1





                    MacOS sed doesn't implement the a command precisely the same as GNU sed, so the above won't work in MacOS without mods - at least as of macOS 10.13 ( see unix.stackexchange.com/a/131940/230763 )

                    – Mike Lutz
                    Jul 13 '18 at 22:19


















                  29














                  Using GNU sed:



                  sed "/cdef/aline1nline2nline3nline4" input.txt


                  If you started with:



                  abcd
                  accd
                  cdef
                  line
                  web


                  this would produce:



                  abcd
                  accd
                  cdef
                  line1
                  line2
                  line3
                  line4
                  line
                  web


                  If you want to save the changes to the file in-place, say:



                  sed -i "/cdef/aline1nline2nline3nline4" input.txt





                  share|improve this answer



















                  • 3





                    I am new to sed but wow I am in love with its power! If you want to append an empty newline first you have to escape the backslash character after the append command like this : sed "/cdef/a\nline1nline2nline3nline4" input.txt. I am not sure why it works like that though, if somebody could explain this would be nice!

                    – hdl
                    Sep 23 '15 at 13:20






                  • 1





                    The current command inserts the line* on every mention of cdef, is there a way to make it so that it only inserts on the first time it encounters cdef and no more?

                    – CMCDragonkai
                    Oct 20 '15 at 13:32






                  • 1





                    MacOS sed doesn't implement the a command precisely the same as GNU sed, so the above won't work in MacOS without mods - at least as of macOS 10.13 ( see unix.stackexchange.com/a/131940/230763 )

                    – Mike Lutz
                    Jul 13 '18 at 22:19
















                  29












                  29








                  29







                  Using GNU sed:



                  sed "/cdef/aline1nline2nline3nline4" input.txt


                  If you started with:



                  abcd
                  accd
                  cdef
                  line
                  web


                  this would produce:



                  abcd
                  accd
                  cdef
                  line1
                  line2
                  line3
                  line4
                  line
                  web


                  If you want to save the changes to the file in-place, say:



                  sed -i "/cdef/aline1nline2nline3nline4" input.txt





                  share|improve this answer













                  Using GNU sed:



                  sed "/cdef/aline1nline2nline3nline4" input.txt


                  If you started with:



                  abcd
                  accd
                  cdef
                  line
                  web


                  this would produce:



                  abcd
                  accd
                  cdef
                  line1
                  line2
                  line3
                  line4
                  line
                  web


                  If you want to save the changes to the file in-place, say:



                  sed -i "/cdef/aline1nline2nline3nline4" input.txt






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Mar 19 '14 at 5:51









                  devnulldevnull

                  84.9k22162183




                  84.9k22162183








                  • 3





                    I am new to sed but wow I am in love with its power! If you want to append an empty newline first you have to escape the backslash character after the append command like this : sed "/cdef/a\nline1nline2nline3nline4" input.txt. I am not sure why it works like that though, if somebody could explain this would be nice!

                    – hdl
                    Sep 23 '15 at 13:20






                  • 1





                    The current command inserts the line* on every mention of cdef, is there a way to make it so that it only inserts on the first time it encounters cdef and no more?

                    – CMCDragonkai
                    Oct 20 '15 at 13:32






                  • 1





                    MacOS sed doesn't implement the a command precisely the same as GNU sed, so the above won't work in MacOS without mods - at least as of macOS 10.13 ( see unix.stackexchange.com/a/131940/230763 )

                    – Mike Lutz
                    Jul 13 '18 at 22:19
















                  • 3





                    I am new to sed but wow I am in love with its power! If you want to append an empty newline first you have to escape the backslash character after the append command like this : sed "/cdef/a\nline1nline2nline3nline4" input.txt. I am not sure why it works like that though, if somebody could explain this would be nice!

                    – hdl
                    Sep 23 '15 at 13:20






                  • 1





                    The current command inserts the line* on every mention of cdef, is there a way to make it so that it only inserts on the first time it encounters cdef and no more?

                    – CMCDragonkai
                    Oct 20 '15 at 13:32






                  • 1





                    MacOS sed doesn't implement the a command precisely the same as GNU sed, so the above won't work in MacOS without mods - at least as of macOS 10.13 ( see unix.stackexchange.com/a/131940/230763 )

                    – Mike Lutz
                    Jul 13 '18 at 22:19










                  3




                  3





                  I am new to sed but wow I am in love with its power! If you want to append an empty newline first you have to escape the backslash character after the append command like this : sed "/cdef/a\nline1nline2nline3nline4" input.txt. I am not sure why it works like that though, if somebody could explain this would be nice!

                  – hdl
                  Sep 23 '15 at 13:20





                  I am new to sed but wow I am in love with its power! If you want to append an empty newline first you have to escape the backslash character after the append command like this : sed "/cdef/a\nline1nline2nline3nline4" input.txt. I am not sure why it works like that though, if somebody could explain this would be nice!

                  – hdl
                  Sep 23 '15 at 13:20




                  1




                  1





                  The current command inserts the line* on every mention of cdef, is there a way to make it so that it only inserts on the first time it encounters cdef and no more?

                  – CMCDragonkai
                  Oct 20 '15 at 13:32





                  The current command inserts the line* on every mention of cdef, is there a way to make it so that it only inserts on the first time it encounters cdef and no more?

                  – CMCDragonkai
                  Oct 20 '15 at 13:32




                  1




                  1





                  MacOS sed doesn't implement the a command precisely the same as GNU sed, so the above won't work in MacOS without mods - at least as of macOS 10.13 ( see unix.stackexchange.com/a/131940/230763 )

                  – Mike Lutz
                  Jul 13 '18 at 22:19







                  MacOS sed doesn't implement the a command precisely the same as GNU sed, so the above won't work in MacOS without mods - at least as of macOS 10.13 ( see unix.stackexchange.com/a/131940/230763 )

                  – Mike Lutz
                  Jul 13 '18 at 22:19













                  13














                  Using awk:



                  awk '/cdef/{print $0 RS "line1" RS "line2" RS "line3" RS "line4";next}1' input.txt 


                  Explanation:




                  • You find the line you want to insert from using /.../

                  • You print the current line using print $0


                  • RS is built-in awk variable that is by default set to new-line.

                  • You add new lines separated by this variable


                  • 1 at the end results in printing of every other lines. Using next before it allows us to prevent the current line since you have already printed it using print $0.





                  $ awk '/cdef/{print $0 RS "line1" RS "line2" RS "line3" RS "line4";next}1' input.txt
                  abcd
                  accd
                  cdef
                  line1
                  line2
                  line3
                  line4
                  line
                  web





                  To make changes to the file you can do:



                  awk '...' input.txt > tmp && mv tmp input.txt





                  share|improve this answer




























                    13














                    Using awk:



                    awk '/cdef/{print $0 RS "line1" RS "line2" RS "line3" RS "line4";next}1' input.txt 


                    Explanation:




                    • You find the line you want to insert from using /.../

                    • You print the current line using print $0


                    • RS is built-in awk variable that is by default set to new-line.

                    • You add new lines separated by this variable


                    • 1 at the end results in printing of every other lines. Using next before it allows us to prevent the current line since you have already printed it using print $0.





                    $ awk '/cdef/{print $0 RS "line1" RS "line2" RS "line3" RS "line4";next}1' input.txt
                    abcd
                    accd
                    cdef
                    line1
                    line2
                    line3
                    line4
                    line
                    web





                    To make changes to the file you can do:



                    awk '...' input.txt > tmp && mv tmp input.txt





                    share|improve this answer


























                      13












                      13








                      13







                      Using awk:



                      awk '/cdef/{print $0 RS "line1" RS "line2" RS "line3" RS "line4";next}1' input.txt 


                      Explanation:




                      • You find the line you want to insert from using /.../

                      • You print the current line using print $0


                      • RS is built-in awk variable that is by default set to new-line.

                      • You add new lines separated by this variable


                      • 1 at the end results in printing of every other lines. Using next before it allows us to prevent the current line since you have already printed it using print $0.





                      $ awk '/cdef/{print $0 RS "line1" RS "line2" RS "line3" RS "line4";next}1' input.txt
                      abcd
                      accd
                      cdef
                      line1
                      line2
                      line3
                      line4
                      line
                      web





                      To make changes to the file you can do:



                      awk '...' input.txt > tmp && mv tmp input.txt





                      share|improve this answer













                      Using awk:



                      awk '/cdef/{print $0 RS "line1" RS "line2" RS "line3" RS "line4";next}1' input.txt 


                      Explanation:




                      • You find the line you want to insert from using /.../

                      • You print the current line using print $0


                      • RS is built-in awk variable that is by default set to new-line.

                      • You add new lines separated by this variable


                      • 1 at the end results in printing of every other lines. Using next before it allows us to prevent the current line since you have already printed it using print $0.





                      $ awk '/cdef/{print $0 RS "line1" RS "line2" RS "line3" RS "line4";next}1' input.txt
                      abcd
                      accd
                      cdef
                      line1
                      line2
                      line3
                      line4
                      line
                      web





                      To make changes to the file you can do:



                      awk '...' input.txt > tmp && mv tmp input.txt






                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Mar 19 '14 at 5:58









                      jaypal singhjaypal singh

                      58.5k1584122




                      58.5k1584122























                          13














                          sed '/^cdef$/r'<(
                          echo "line1"
                          echo "line2"
                          echo "line3"
                          echo "line4"
                          ) -i -- input.txt





                          share|improve this answer
























                          • works nicely and makes it much more readable

                            – KoZm0kNoT
                            Aug 23 '18 at 16:26













                          • Missed this good answer. Shorter but less readable is sed '/^cdef$/r' <(printf "%sn" line{1..4}) -i -- input.txt.

                            – Walter A
                            Jan 2 at 10:40
















                          13














                          sed '/^cdef$/r'<(
                          echo "line1"
                          echo "line2"
                          echo "line3"
                          echo "line4"
                          ) -i -- input.txt





                          share|improve this answer
























                          • works nicely and makes it much more readable

                            – KoZm0kNoT
                            Aug 23 '18 at 16:26













                          • Missed this good answer. Shorter but less readable is sed '/^cdef$/r' <(printf "%sn" line{1..4}) -i -- input.txt.

                            – Walter A
                            Jan 2 at 10:40














                          13












                          13








                          13







                          sed '/^cdef$/r'<(
                          echo "line1"
                          echo "line2"
                          echo "line3"
                          echo "line4"
                          ) -i -- input.txt





                          share|improve this answer













                          sed '/^cdef$/r'<(
                          echo "line1"
                          echo "line2"
                          echo "line3"
                          echo "line4"
                          ) -i -- input.txt






                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Jul 30 '18 at 0:32









                          rindealrindeal

                          573714




                          573714













                          • works nicely and makes it much more readable

                            – KoZm0kNoT
                            Aug 23 '18 at 16:26













                          • Missed this good answer. Shorter but less readable is sed '/^cdef$/r' <(printf "%sn" line{1..4}) -i -- input.txt.

                            – Walter A
                            Jan 2 at 10:40



















                          • works nicely and makes it much more readable

                            – KoZm0kNoT
                            Aug 23 '18 at 16:26













                          • Missed this good answer. Shorter but less readable is sed '/^cdef$/r' <(printf "%sn" line{1..4}) -i -- input.txt.

                            – Walter A
                            Jan 2 at 10:40

















                          works nicely and makes it much more readable

                          – KoZm0kNoT
                          Aug 23 '18 at 16:26







                          works nicely and makes it much more readable

                          – KoZm0kNoT
                          Aug 23 '18 at 16:26















                          Missed this good answer. Shorter but less readable is sed '/^cdef$/r' <(printf "%sn" line{1..4}) -i -- input.txt.

                          – Walter A
                          Jan 2 at 10:40





                          Missed this good answer. Shorter but less readable is sed '/^cdef$/r' <(printf "%sn" line{1..4}) -i -- input.txt.

                          – Walter A
                          Jan 2 at 10:40











                          1














                          This answer is easy to understand




                          • Copy before the pattern

                          • Add your lines

                          • Copy after the pattern


                          • Replace original file



                            FILENAME='app/Providers/AuthServiceProvider.php'




                          STEP 1 copy until the pattern



                          sed '/THEPATTERNYOUARELOOKINGFOR/Q' $FILENAME >>${FILENAME}_temp


                          STEP 2 add your lines



                          cat << 'EOL' >> ${FILENAME}_temp

                          HERE YOU COPY AND
                          PASTE MULTIPLE
                          LINES, ALSO YOU CAN
                          //WRITE COMMENTS

                          AND NEW LINES
                          AND SPECIAL CHARS LIKE $THISONE

                          EOL


                          STEP 3 add the rest of the file



                          grep -A 9999 'THEPATTERNYOUARELOOKINGFOR' $FILENAME >>${FILENAME}_temp


                          REPLACE original file



                          mv ${FILENAME}_temp $FILENAME


                          if you need variables, in step 2 replace 'EOL' with EOL



                          cat << EOL >> ${FILENAME}_temp

                          this variable will expand: $variable1

                          EOL





                          share|improve this answer




























                            1














                            This answer is easy to understand




                            • Copy before the pattern

                            • Add your lines

                            • Copy after the pattern


                            • Replace original file



                              FILENAME='app/Providers/AuthServiceProvider.php'




                            STEP 1 copy until the pattern



                            sed '/THEPATTERNYOUARELOOKINGFOR/Q' $FILENAME >>${FILENAME}_temp


                            STEP 2 add your lines



                            cat << 'EOL' >> ${FILENAME}_temp

                            HERE YOU COPY AND
                            PASTE MULTIPLE
                            LINES, ALSO YOU CAN
                            //WRITE COMMENTS

                            AND NEW LINES
                            AND SPECIAL CHARS LIKE $THISONE

                            EOL


                            STEP 3 add the rest of the file



                            grep -A 9999 'THEPATTERNYOUARELOOKINGFOR' $FILENAME >>${FILENAME}_temp


                            REPLACE original file



                            mv ${FILENAME}_temp $FILENAME


                            if you need variables, in step 2 replace 'EOL' with EOL



                            cat << EOL >> ${FILENAME}_temp

                            this variable will expand: $variable1

                            EOL





                            share|improve this answer


























                              1












                              1








                              1







                              This answer is easy to understand




                              • Copy before the pattern

                              • Add your lines

                              • Copy after the pattern


                              • Replace original file



                                FILENAME='app/Providers/AuthServiceProvider.php'




                              STEP 1 copy until the pattern



                              sed '/THEPATTERNYOUARELOOKINGFOR/Q' $FILENAME >>${FILENAME}_temp


                              STEP 2 add your lines



                              cat << 'EOL' >> ${FILENAME}_temp

                              HERE YOU COPY AND
                              PASTE MULTIPLE
                              LINES, ALSO YOU CAN
                              //WRITE COMMENTS

                              AND NEW LINES
                              AND SPECIAL CHARS LIKE $THISONE

                              EOL


                              STEP 3 add the rest of the file



                              grep -A 9999 'THEPATTERNYOUARELOOKINGFOR' $FILENAME >>${FILENAME}_temp


                              REPLACE original file



                              mv ${FILENAME}_temp $FILENAME


                              if you need variables, in step 2 replace 'EOL' with EOL



                              cat << EOL >> ${FILENAME}_temp

                              this variable will expand: $variable1

                              EOL





                              share|improve this answer













                              This answer is easy to understand




                              • Copy before the pattern

                              • Add your lines

                              • Copy after the pattern


                              • Replace original file



                                FILENAME='app/Providers/AuthServiceProvider.php'




                              STEP 1 copy until the pattern



                              sed '/THEPATTERNYOUARELOOKINGFOR/Q' $FILENAME >>${FILENAME}_temp


                              STEP 2 add your lines



                              cat << 'EOL' >> ${FILENAME}_temp

                              HERE YOU COPY AND
                              PASTE MULTIPLE
                              LINES, ALSO YOU CAN
                              //WRITE COMMENTS

                              AND NEW LINES
                              AND SPECIAL CHARS LIKE $THISONE

                              EOL


                              STEP 3 add the rest of the file



                              grep -A 9999 'THEPATTERNYOUARELOOKINGFOR' $FILENAME >>${FILENAME}_temp


                              REPLACE original file



                              mv ${FILENAME}_temp $FILENAME


                              if you need variables, in step 2 replace 'EOL' with EOL



                              cat << EOL >> ${FILENAME}_temp

                              this variable will expand: $variable1

                              EOL






                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered May 22 '17 at 20:59









                              lalolalo

                              387138




                              387138























                                  0














                                  I needed to template a few files with minimal tooling and for me the issue with above sed -e '/../r file.txt is that it only appends the file after it prints out the rest of the match, it doesn't replace it.



                                  This doesn't do it (all matches are replaced and pattern matching continues from same point)



                                  #!/bin/bash

                                  TEMPDIR=$(mktemp -d "${TMPDIR:-/tmp/}$(basename $0).XXXXXXXXXXXX")
                                  # remove on exit
                                  trap "rm -rf $TEMPDIR" EXIT

                                  DCTEMPLATE=$TEMPDIR/dctemplate.txt
                                  DCTEMPFILE=$TEMPDIR/dctempfile.txt

                                  # template that will replace
                                  printf "0replacement
                                  1${SHELL} data
                                  2anotherlinenoEOL" > $DCTEMPLATE

                                  # test data
                                  echo -e "xxy n987 nxx xxn yz yxxyy" > $DCTEMPFILE

                                  # print original for debug
                                  echo "---8<--- $DCTEMPFILE"
                                  cat $DCTEMPFILE
                                  echo "---8<--- $DCTEMPLATE"
                                  cat $DCTEMPLATE
                                  echo "---8<---"

                                  # replace 'xx' -> contents of $DCTEMPFILE
                                  perl -e "our $fname = '${DCTEMPLATE}';" -pe 's/xx/`cat $fname`/eg' ${DCTEMPFILE}





                                  share|improve this answer




























                                    0














                                    I needed to template a few files with minimal tooling and for me the issue with above sed -e '/../r file.txt is that it only appends the file after it prints out the rest of the match, it doesn't replace it.



                                    This doesn't do it (all matches are replaced and pattern matching continues from same point)



                                    #!/bin/bash

                                    TEMPDIR=$(mktemp -d "${TMPDIR:-/tmp/}$(basename $0).XXXXXXXXXXXX")
                                    # remove on exit
                                    trap "rm -rf $TEMPDIR" EXIT

                                    DCTEMPLATE=$TEMPDIR/dctemplate.txt
                                    DCTEMPFILE=$TEMPDIR/dctempfile.txt

                                    # template that will replace
                                    printf "0replacement
                                    1${SHELL} data
                                    2anotherlinenoEOL" > $DCTEMPLATE

                                    # test data
                                    echo -e "xxy n987 nxx xxn yz yxxyy" > $DCTEMPFILE

                                    # print original for debug
                                    echo "---8<--- $DCTEMPFILE"
                                    cat $DCTEMPFILE
                                    echo "---8<--- $DCTEMPLATE"
                                    cat $DCTEMPLATE
                                    echo "---8<---"

                                    # replace 'xx' -> contents of $DCTEMPFILE
                                    perl -e "our $fname = '${DCTEMPLATE}';" -pe 's/xx/`cat $fname`/eg' ${DCTEMPFILE}





                                    share|improve this answer


























                                      0












                                      0








                                      0







                                      I needed to template a few files with minimal tooling and for me the issue with above sed -e '/../r file.txt is that it only appends the file after it prints out the rest of the match, it doesn't replace it.



                                      This doesn't do it (all matches are replaced and pattern matching continues from same point)



                                      #!/bin/bash

                                      TEMPDIR=$(mktemp -d "${TMPDIR:-/tmp/}$(basename $0).XXXXXXXXXXXX")
                                      # remove on exit
                                      trap "rm -rf $TEMPDIR" EXIT

                                      DCTEMPLATE=$TEMPDIR/dctemplate.txt
                                      DCTEMPFILE=$TEMPDIR/dctempfile.txt

                                      # template that will replace
                                      printf "0replacement
                                      1${SHELL} data
                                      2anotherlinenoEOL" > $DCTEMPLATE

                                      # test data
                                      echo -e "xxy n987 nxx xxn yz yxxyy" > $DCTEMPFILE

                                      # print original for debug
                                      echo "---8<--- $DCTEMPFILE"
                                      cat $DCTEMPFILE
                                      echo "---8<--- $DCTEMPLATE"
                                      cat $DCTEMPLATE
                                      echo "---8<---"

                                      # replace 'xx' -> contents of $DCTEMPFILE
                                      perl -e "our $fname = '${DCTEMPLATE}';" -pe 's/xx/`cat $fname`/eg' ${DCTEMPFILE}





                                      share|improve this answer













                                      I needed to template a few files with minimal tooling and for me the issue with above sed -e '/../r file.txt is that it only appends the file after it prints out the rest of the match, it doesn't replace it.



                                      This doesn't do it (all matches are replaced and pattern matching continues from same point)



                                      #!/bin/bash

                                      TEMPDIR=$(mktemp -d "${TMPDIR:-/tmp/}$(basename $0).XXXXXXXXXXXX")
                                      # remove on exit
                                      trap "rm -rf $TEMPDIR" EXIT

                                      DCTEMPLATE=$TEMPDIR/dctemplate.txt
                                      DCTEMPFILE=$TEMPDIR/dctempfile.txt

                                      # template that will replace
                                      printf "0replacement
                                      1${SHELL} data
                                      2anotherlinenoEOL" > $DCTEMPLATE

                                      # test data
                                      echo -e "xxy n987 nxx xxn yz yxxyy" > $DCTEMPFILE

                                      # print original for debug
                                      echo "---8<--- $DCTEMPFILE"
                                      cat $DCTEMPFILE
                                      echo "---8<--- $DCTEMPLATE"
                                      cat $DCTEMPLATE
                                      echo "---8<---"

                                      # replace 'xx' -> contents of $DCTEMPFILE
                                      perl -e "our $fname = '${DCTEMPLATE}';" -pe 's/xx/`cat $fname`/eg' ${DCTEMPFILE}






                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered Nov 26 '18 at 15:47









                                      Pasi SavolainenPasi Savolainen

                                      1,90811631




                                      1,90811631























                                          0














                                          You can use awk for inserting output of some command in the middle of input.txt.

                                          The lines to be inserted can be the output of a cat otherfile, ls -l or 4 lines with a number generated by printf.



                                          awk 'NR==FNR {a[NR]=$0;next}
                                          {print}
                                          /cdef/ {for (i=1; i <= length(a); i++) { print a[i] }}'
                                          <(printf "%sn" line{1..4}) input.txt





                                          share|improve this answer






























                                            0














                                            You can use awk for inserting output of some command in the middle of input.txt.

                                            The lines to be inserted can be the output of a cat otherfile, ls -l or 4 lines with a number generated by printf.



                                            awk 'NR==FNR {a[NR]=$0;next}
                                            {print}
                                            /cdef/ {for (i=1; i <= length(a); i++) { print a[i] }}'
                                            <(printf "%sn" line{1..4}) input.txt





                                            share|improve this answer




























                                              0












                                              0








                                              0







                                              You can use awk for inserting output of some command in the middle of input.txt.

                                              The lines to be inserted can be the output of a cat otherfile, ls -l or 4 lines with a number generated by printf.



                                              awk 'NR==FNR {a[NR]=$0;next}
                                              {print}
                                              /cdef/ {for (i=1; i <= length(a); i++) { print a[i] }}'
                                              <(printf "%sn" line{1..4}) input.txt





                                              share|improve this answer















                                              You can use awk for inserting output of some command in the middle of input.txt.

                                              The lines to be inserted can be the output of a cat otherfile, ls -l or 4 lines with a number generated by printf.



                                              awk 'NR==FNR {a[NR]=$0;next}
                                              {print}
                                              /cdef/ {for (i=1; i <= length(a); i++) { print a[i] }}'
                                              <(printf "%sn" line{1..4}) input.txt






                                              share|improve this answer














                                              share|improve this answer



                                              share|improve this answer








                                              edited Jan 2 at 10:21

























                                              answered Dec 31 '18 at 11:41









                                              Walter AWalter A

                                              10.9k21032




                                              10.9k21032






























                                                  draft saved

                                                  draft discarded




















































                                                  Thanks for contributing an answer to Stack Overflow!


                                                  • Please be sure to answer the question. Provide details and share your research!

                                                  But avoid



                                                  • Asking for help, clarification, or responding to other answers.

                                                  • Making statements based on opinion; back them up with references or personal experience.


                                                  To learn more, see our tips on writing great answers.




                                                  draft saved


                                                  draft discarded














                                                  StackExchange.ready(
                                                  function () {
                                                  StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f22497246%2finsert-multiple-lines-into-a-file-after-specified-pattern-using-shell-script%23new-answer', 'question_page');
                                                  }
                                                  );

                                                  Post as a guest















                                                  Required, but never shown





















































                                                  Required, but never shown














                                                  Required, but never shown












                                                  Required, but never shown







                                                  Required, but never shown

































                                                  Required, but never shown














                                                  Required, but never shown












                                                  Required, but never shown







                                                  Required, but never shown







                                                  Popular posts from this blog

                                                  Monofisismo

                                                  Angular Downloading a file using contenturl with Basic Authentication

                                                  Olmecas