0

我的文字如下所示:

猫抓 猫

一斤

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

sed "s/猫/狗/"

我的结果是:



猫鼠
一斤

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

4

4 回答 4

2

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

sed 's/cat/dog/g'

G

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

于 2013-01-21T17:19:44.613 回答
2

如果您只想在部分单词匹配的情况下仅用狗替换猫:

$ 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
于 2013-01-21T19:41:38.280 回答
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
于 2013-01-22T05:06:32.073 回答
1

awk 解决方案

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

于 2013-01-23T02:56:50.640 回答