For some problems like matching a pattern over an unknown number of lines or "replace the last occurence of ..." the option -z
of GNU sed
is really helpful. How can I achieve the same thing portable?
Example: I have a file
yellow, green,
blue, black, purple,
orange,
white, red, brown
are some colours
and I want to replace the last comma of the file with and
. Note that it is unknown in which line or where in that line the comma is. With GNU sed
I can do
sed -z 's/\(.*\),/ \1 and/'
to get the desired output
yellow, green,
blue, black, purple,
orange,
white, red and brown
are some colours
How can I do it in a portable way, that will run with any POSIX sed
?
perl -0777
as an option for portable solution – Sundeep Aug 01 '19 at 08:11sed
easily. Usually users already have the right approach, they just need a hint to the-z
option or this portable pattern. But they need a compact explanation not found in the answers linked by @Sundeep . Please note that usingawk
orperl
orpython
usually involves programming, whilesed
is a different appraoch without programming, preferred by a number of people. – Philippos Aug 01 '19 at 13:57perl -p -e 's/foo/bar/'
. Orperl -p -0777 -e 's/foo/bar/g'
to process the entire input as one string. Or use-00
to process the input one paragraph at a time (paras are separated by one or more blank lines). So if you have perl installed, but not a sed that understands -Z, perl is a good substitute. – cas Aug 03 '19 at 01:19