我正在尝试从字符串中删除特定单词。我无法用简单的全局字符串替换“ the”来清空字符串,因为“ the”可能是字符串中单词的一部分。
word: "the"
string: "the_ad_an_feta_cfr_era_the_iop_the"
output: "ad_an_feta_cfr_era_iop"
“ the”一词可能出现在字符串的开头,中间或结尾多次,因此我必须考虑分隔符和字符串的开头/结尾。
我可以用一个正则表达式处理所有这些问题,还是应该求助于循环,但是如何在sed中指定多个模式?
sed 's/the//g' <<< "the_ad_feta_cfr_era_the_iop_the"
然后,如果我想从同一字符串中删除几个单词,该怎么办?不仅删除“ the”,还删除“ is”,“ an”。 不用循环就可以在正则表达式中所有这一切吗?
word: "the", "an", "is"
input: "the_ad_an_feta_cfr_era_the_iop_the"
output: "ad_feta_cfr_era_iop"
答案 0 :(得分:1)
看看这个sed
:
$ string='the_ad_an_feta_cfr_era_the_iop_the'
$ sed -E -e ':a' -e 's/(^|_)(the|an|is|feta)(_|$)/\1/g;ta' -e 's/_$//' <<< "$string"
ad_cfr_era_iop
请注意,sed
的行为在Unix变体之间是不同的。您的sed
似乎在标签后需要换行符(或多个-e
选项)。进一步阅读:
没有标签的版本与@Cyrus' answer基本相同,但支持带空格的“项目”:
$ string='the_ad_an_feta_cfr_era_the cfr_the_iop_the'
$ sed -E -e 's/_/__/g;s/(^|_)(the|an|is|feta)(_|$)//g;s/_+/_/g;s/^_//;s/_$//' <<< "$string"
ad_cfr_era_the cfr_iop