I am using sed to find and replace items, e.g.:
sed -i 's/fish/bear/g' ./file.txt
I want to limit this to only change items which do not have a letter or number before or after, e.g.:
The fish ate the worm.would change, because only spaces are before and after.The lionfish ate the worm.would not change, because there is a letter beforefish.
How can I find and replace some items, but not if at least one letter or number appears immediately before or after?
Use a negative character class before and after
fish, like so:\(^\|[^[:alnum:]]\)fish\($\|[^[:alnum:]]\). This says:This guarantees that the characters immediately preceding and immediately following
fishare not alphanumeric.