sed A Value In A Column

trying to replace a specific value in a column with sed. this is what I have but can't get it to work, replace dog with kitty if dog is in the 3rd column and bunny in the 1st column if bird is there

bird lizard fish
bird lizard dog
bird lizard fish
sed '/bird/s/^/bunny/1;'/dog/s/^/kitty/3' file

trying different iterations but just can't seem to get it to work

this would be the output

bunny lizard fish
bunny lizard kitty
bunny lizard fish

sed might not be the optimal tool for this, but try

sed 's/^bird/bunny/;s/\([^ ]* [^ ]* \)dog/\1kitty/' file
bunny lizard fish
bunny lizard kitty
bunny lizard fish

it works but I don't understand why

In it it simplest form using anchors ( ^ and $ ):

sed 's/^bird/bunny/; s/dog$/kitty/' file

or depending of input variation, a little better, also using spaces to mark the other side of the word boundary:

sed 's/^bird /bunny /; s/ dog$/ kitty/' file
2 Likes