如果单词的一部分匹配,则替换

时间:2013-01-21 17:19:02

标签: sed

我的文字如下:

  


  赶上
  cat_mouse
  斤

我想用“狗”代替“猫” 当我做的时候

  

sed“s / cat / dog /”

我的结果是:

  


  赶上
  cat_mouse
  斤

如果只有部分字符匹配,如何用sed替换?

4 个答案:

答案 0 :(得分:2)

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

sed 's/cat/dog/g'
  

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

答案 1 :(得分:2)

如果您只想在 dog 中替换 cat ,只有部分字词匹配:

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

我使用Positive Look Around,请参阅http://www.perlmonks.org/?node_id=518444

如果你真的想要sed:

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

答案 2 :(得分:2)

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

{{1}}

答案 3 :(得分:1)

awk解决方案

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

相关问题