Reputation: 28329
My text looks like this:
cat
catch
cat_mouse
catty
I want to replace "cat" with "dog".
When I do
sed "s/cat/dog/"
my result is:
dog
catch
cat_mouse
catty
How do I replace with sed if only part of the word matches?
Upvotes: 0
Views: 1547
Reputation: 31548
awk solution for this
awk '{gsub("cat","dog",$0); print}' temp.txt
Upvotes: 1
Reputation: 23095
bash-3.00$ cat t
cat
catch
cat_mouse
catty
To replace cat
only if it is part of a string
bash-3.00$ sed 's/cat\([^$]\)/dog\1/' t
cat
dogch
dog_mouse
dogty
To replace all occurrences of cat
:
bash-3.00$ sed 's/cat/dog/' t
dog
dogch
dog_mouse
dogty
Upvotes: 2
Reputation: 185025
If you want to replace only cat by dog only if part of the word matches :
$ perl -pe 's/cat(?=.)/dog/' file.txt
cat
dogch
dog_mouse
dogty
I use Positive Look Around, see http://www.perlmonks.org/?node_id=518444
If you really want sed :
sed '/^cat$/!s/cat/dog/' file.txt
Upvotes: 2
Reputation: 185025
There's a mistake :
You lack the g
modifier
sed 's/cat/dog/g'
g
Apply the replacement to all matches to the regexp, not just the first.
See
Upvotes: 2