Mutiline delete in FreeBSD

拜拜、爱过 提交于 2020-07-21 03:09:57

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!