【问题标题】:Use sed to find and replace all instances of a pattern使用 sed 查找和替换模式的所有实例
【发布时间】:2016-04-30 12:14:36
【问题描述】:

我不太擅长 sed。只是看起来很复杂。但是我已经学会了如何用另一个字符串替换一个字符串的所有实例

sed 's/replace-this/with-this/FLAG'

但是,如果我想说用水果替换所有以“a”开头并有第三个字母“p”的单词,我该怎么做?

【问题讨论】:

  • 我的意思是说我想将所有以“a”开头并有第三个字母“p”的单词替换为单词“fruit”。
  • 你必须使用sed 吗?还是纯 Bash 解决方案可以吗?
  • 如果 sed 是可选的并且可以接受纯 bash 解决方案,那么您可能想看看这个:例如,read -ra arr <<< "$var"; printf -v var '%s' "${arr[*]//a?p*/fruit}";var="apple is a fruit"

标签: regex bash sed


【解决方案1】:

给定:

$ echo "$tgt"
app
apple
applesauce
grape
gum
apple is a fruit
text apple and pears

你可以这样做:

$ echo "$tgt" | sed 's/a.p.*/fruit/'
fruit
fruit
fruit
grape
gum
fruit
text fruit

如果您只想要单词(而不是该行的其余部分),您可以这样做:

$ echo "$tgt" | sed -E 's/a.p[a-zA-Z]*/fruit/'
fruit
fruit
fruit
grape
gum
fruit is a fruit
text fruit and pears

【讨论】:

  • apple is a fruit 这一行怎么样?
  • 我认为apple is a fruit 应该变成fruit is a fruit
  • 如所写,它将替换a.p 之后的行的其余部分,因此apple is a fruit 和行的其余部分将变为fruit
  • 对不起。我应该澄清一些事情。我只想替换单词而不是整行。因此,正如上面提到的 pfnuesel,我想将“apple is a fruit”这一行更改为“fruit is a fruit”,并将“appetizers etc”这一行更改为“fruits etc”
  • 也感谢您澄清fruit is a fruit:p
【解决方案2】:

这可能对你有用(GNU sed):

sed 's/\<a\wp\w*\>/fruit/g' file

这使用\&lt; 开头的单词边界作为单词的开始标记,后跟 \&gt; 结束词边界,将被全局替换为词 fruit

【讨论】:

  • sed 不幸的是没有统一的word boundaries 感觉。 \&lt;\&gt; 仅适用于 GNU
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-01-12
  • 2017-02-14
  • 2012-12-29
  • 1970-01-01
  • 2020-08-05
  • 2019-03-29
  • 2021-10-06
相关资源
最近更新 更多