我的文字如下:
猫
赶上
cat_mouse
斤
我想用“狗”代替“猫” 当我做的时候
sed“s / cat / dog /”
我的结果是:
狗
赶上
cat_mouse
斤
如果只有部分字符匹配,如何用sed替换?
答案 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