问题
How can we make this work in FreeBSD?
Multiple line delete block containing a pattern in FreeBSD.
sed '/{START-TAG/{:a;N;/END-TAG}/!ba};/ID: 222/d' data.txt
See sed multiline delete with pattern.
回答1:
In FreeBSD sed
, you can't separate commands using a semi-colon. However, you may use -e
chained commands:
sed -e '/{START-TAG/{' -e :a -e N -e '/END-TAG}/!ba' -e '}' -e '/ID: 222/d' file > outputfile
To save the contents inline, use
sed -i '' -e '/{START-TAG/{' -e :a -e N -e '/END-TAG}/!ba' -e '}' -e '/ID: 222/d' file
回答2:
Don't use sed for anything that involves multiple lines, just use awk for a robust, portable solution. Given the sample input from the question you referenced, if the blocks are always separated by blank lines:
$ awk -v RS= -v ORS='\n\n' '!/ID: 222/' file
{START-TAG
foo bar
ID: 111
foo bar
END-TAG}
{START-TAG
foo bar
ID: 333
foo bar
END-TAG}
otherwise:
$ awk '/{START-TAG/{f=1} f{rec=rec $0 ORS} /END-TAG}/{if (rec !~ /ID: 222/) print rec; rec=f=""}' file
{START-TAG
foo bar
ID: 111
foo bar
END-TAG}
{START-TAG
foo bar
ID: 333
foo bar
END-TAG}
Both of those scripts will work using any awk in any shell on every UNIX box.
来源:https://stackoverflow.com/questions/62459753/mutiline-delete-in-freebsd