Inserting a file into another file after the 1st occurrence of a pattern

sedtext processing

I want to insert the contents of file1 into file2 after a matching PATTERN. I want to do it only after the first occurrence of the PATTERN.

I would like to know the modification I need to make to the following command for my needs.

sed -i "/PATTERN/r file1" file2

Best Answer

sed '/PATTERN/{
       r file1
       :a
       n
       ba
     }' file2

:a, n, ba is just a cycle that printouts the whole file content after the PATTERN till the end. and note, that those 6 lines are just one command, but newline is needed to delimit the next sed command after r, : and b.

additional info from info sed :

`n'
     If auto-print is not disabled, print the pattern space, then,
     regardless, replace the pattern space with the next line of input.
     If there is no more input then `sed' exits without processing any
     more commands.

`: LABEL'
     [No addresses allowed.]

     Specify the location of LABEL for branch commands.  In all other
     respects, a no-op.

`b LABEL'
     Unconditionally branch to LABEL.  The LABEL may be omitted, in
     which case the next cycle is started.
Related Question