I need to add a new line before any line containing a pattern where we can assume that the pattern is always the first string of the current line. For example
This is a
pattern
This is a
pattern
I can add a new line with the sed
command
sed -i 's/pattern\+/\n&/g' file
to get the output
This is a
pattern
This is a
pattern
To prevent multiple new lines being added (in case of multiple execution) I want to check whether the line before the pattern is empty. I know I can do that with
if [ "$line" == "" ]; then
But how do I determine the previous line, of a matching pattern, in the first place?
EDIT: Pattern can occur multiple times.
Best Answer
You could store the previous line in the hold space:
It would be more legible with
awk
though:Like the GNU implementations of
sed
has a-i
option for in-place editing, the GNU implementation ofawk
as-i inplace
for that.