Easier if you saved those lines in a text file, e.g. infile
then used ed
to edit your files in-place:
for f in ./*.txt; do
ed -s "$f" <<\IN
.t.
?[kK][eE][yY][wW][oO][rR][dD]?-1 r infile
$d
w
q
IN
done
If you just wanted to insert some text (not the content of a file), it's similar:
for f in ./*.txt; do
ed -s "$f" <<\IN
.t.
?[kK][eE][yY][wW][oO][rR][dD]?-1 s/$\
some_text\
more_text\
last\\_\&_line
$d
w
q
IN
Replace w
with ,p
to see what it does without modifying the files.
Note that backslashes, ampersands and delimiters have to be escaped in the RHS of a substitution. The same applies to newlines, except the last one.
How it works ? Well, duplicate the last line, search for your keyword backwards, insert the text or the content of the file before that line, delete the duplicated last line, write, quit.
Sure, if you don't need to edit those files in place and just want to print the modified versions, like Zanna does, you don't need arcane text editors with a syntax from another age... You can do it with a single sed
invocation - and because Wildcard kindly reminded me that in this family of editors there's a dedicated command to i
nsert text before a match let's use that and some branching:
sed -s '1{h;$!d;b end
}
/keyword/I{H;$!d
}
//{x;p;$!d
}
:end
${x;/keyword/Ii\
some_text_here\
more_text_here\
and_a\\_backslash
}' ./*.txt
This only works with gnu sed
though... with other sed
s you'll have to run a loop (this time without the branch part so as to have a blank line between each file content):
for f in ./*.txt; do
sed -s '/[kK][eE][yY][wW][oO][rR][dD]/{H;$!d
}
//{x;p;$!d
}
${x;/[kK][eE][yY][wW][oO][rR][dD]/i\
some_text_here\
more_text_here\
and_a\\_backslash
}' "$f"
done
As you can see even with i
nsert, one still have to escape backslashes and newlines (except the last one). Other than that, it's simple: it just accumulates lines in the hold buffer and exchanges when encountering a match; on last line it exchanges again and inserts the text before the match, if any.
SEARCHWORD
only occurs once in your data...sed
aside), but we still don't know where the extra data should come from...