Shell: delete every second match against a regex in a file

夙愿已清 提交于 2019-12-11 19:34:13

问题


Say I have come up with a regex matching a piece of data; the regex contains 2 sed groups (sub-expressions enclosed in ( and )). Also say that this regex is duplicated 9 times to match a whole line. The problem I am facing is how to delete (in an elegant way) every second match against the regex.


回答1:


Let's say you have the following string and want to remove the occurrences of bar:

foo bar foo bar foo bar

You can use the following sed command, note the option g which makes the substitution happen as many times as possible:

sed -r 's/([a-z]+) ([a-z]+)/\1/g' <<< 'foo bar foo bar foo bar'

Output: foo foo foo.

However this would not work with a string where the number of words is not even. I would make the second capturing group optional using the * quantifier to make the above commmand even work with such strings:

sed -r 's/([a-z]+) ([a-z]+)*/\1/g' <<< 'foo bar foo bar foo bar foo'

Output: foo foo foo foo.



来源:https://stackoverflow.com/questions/29703702/shell-delete-every-second-match-against-a-regex-in-a-file

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