2

Files get messed up with multiple lines containing foo or bar. I want to remove all of them and append one line of each at the end.

So, given a file

some stuff
foo1
foo2
bar=42
some other stuff
bar
foo
more stuff

the sed script should return

some stuff
some other stuff
more stuff
foo
bar

I tried with sed '/foo/d;/bar/d;$s/$/\nfoo\nbar/' which works as long as the last line contains neither foo nor bar and the file is not empty.

How to do make it work even with foo in the last line? I'd like to stick to sed, becuase the whole script should do more than just this. Of source I could append my lines with echo after the script, but I wonder if there is no all-in-one-solution.

Edit: The empty file case doesn't need to be handled.

0

2 Answers 2

0

You should add a second condition - delete only if not the last line and on the last line use append instead of substitute deleting the line afterwards if it matches e.g.

sed -E '/foo|bar/{$!d
}
${a\
foo\
bar
//d
}' infile
0
0
( sed -e '/foo/d' -e '/bar/d' data.in; cat <<END
foo
bar
END
) >data.out

Deleting the unwanted lines with sed then simply adding the wanted trailing lines with cat and outputting to a new file.

Alternatively using printf instead of cat:

( sed -e '/foo/d' -e '/bar/d' data.in; printf 'foo\nbar\n' ) >data.out

Or, in two steps,

sed -e '/foo/d' -e '/bar/d' data.in >data.out
printf 'foo\nbar\n' >>data.out

This has the benefit of being clear and easily maintainable.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .