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.
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
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 xx\n 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}
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.
suppose you have a file called 'insert.txt' containing the lines you want to add:
line1
line2
line3
line4
If the PATTERN 'cdef' REPEATS MULTIPLE TIMES in your input.txt file, and you want to add the lines from 'insert.txt' after ALL occurrences of the pattern 'cdef' , then a easy solution is:
sed -i -e '/cdef/r insert.txt' input.txt
but, if the PATTERN 'cdef' REPEATS MULTIPLE TIMES in your input.txt file, and you want to add the lines from 'insert.txt' ONLY AFTER THE FIRST OCCURRENCE of the pattern, a beautiful solution is:
printf "%s\n" "/cdef/r insert.txt" w | ed -s input.txt
Both solution will work fine in case the pattern happens only once in your input.txt file.