This is how I am adding text before first pattern, I want to add after last pattern
FILE_NAME=\"folder/myfile.c++\"
STR_TO_ADD=\"string tha
The solution by user0 is close, but if the last match falls on the last line of the file, it will find the previous one. Instead, go to the first line and search backward:
1
?^$PATTERN
a
$STR_TO_ADD
.
I just posted this on my @ed1conf account a couple days ago so it's fresh in my mind.
Additionally, if you're trying to add before the text (the example you already have), it will fail if the first match is on the first line because the "-1
" goes before the start of the file. Instead, use the "i
" command to insert the text rather than append it:
$
/^$PATTERN
i
$STR_TO_ADD
.
You might also need to ensure that "$STR_TO_ADD
" doesn't contain any lines containing a single period or the variable-expansion will prematurely terminate the i
nsertion (or a
ppending).
Go to last line of file and search pattern in backward direction.
FILE_NAME="folder/myfile.c++"
STR_TO_ADD="string that i want to add"
PATTERN="banana"
ed $FILE_NAME 2>NULL 1>NULL<<EOF
$
?^$PATTERN
a
$STR_TO_ADD
.
wq
EOF
$
last line of file.
?^$PATTERN
search pattern in backward direction from current line.