【问题标题】:sed replace if part of word matches如果部分单词匹配,则 sed 替换
【发布时间】:2013-01-23 10:56:50
【问题描述】:

我的文字是这样的:


赶上
猫鼠
一斤

我想用“狗”代替“猫”。
当我这样做时

sed "s/cat/dog/"

我的结果是:


赶上
猫鼠
一斤

如果只有部分单词匹配,如何用 sed 替换?

【问题讨论】:

  • 你确定吗? sed 's/cat/dog/' 应该在cat_mouse 行中进行替换。您是否正确表示了输入数据。 (例如,它实际上都在一行上,而不是在不同的行上吗?)
  • 更好地提供您期望的输出。

标签: sed


【解决方案1】:

有一个错误: 你缺少g 修饰符

sed 's/cat/dog/g'

g

Apply the replacement to all matches to the regexp, not just the first.

【讨论】:

  • 这无关紧要,除非提问者歪曲了输入数据。
【解决方案2】:

如果您只想在部分单词匹配时将 cat 替换为 dog

$ perl -pe 's/cat(?=.)/dog/' file.txt
cat
dogch
dog_mouse
dogty

我使用正面环视,请参阅http://www.perlmonks.org/?node_id=518444

如果你真的想要 sed:

sed '/^cat$/!s/cat/dog/' file.txt

【讨论】:

    【解决方案3】:
    bash-3.00$ cat t
    cat
    catch
    cat_mouse
    catty
    

    仅当 cat 是字符串的一部分时才替换它

    bash-3.00$ sed 's/cat\([^$]\)/dog\1/' t
    cat
    dogch
    dog_mouse
    dogty
    

    替换所有出现的cat

    bash-3.00$ sed 's/cat/dog/' t
    dog
    dogch
    dog_mouse
    dogty
    

    【讨论】:

      【解决方案4】:

      awk 解决方案

      awk '{gsub("cat","dog",$0); print}' temp.txt

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-06-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-06-04
        • 1970-01-01
        • 2012-03-07
        • 1970-01-01
        相关资源
        最近更新 更多