I need to replace a few words with other words.
For example, "apple" with "FRUIT" in file , only in these 4 situations:
_apple_ , has a space before and after.[apple_ , has a square opening bracket before and a space after._apple] , has a space before and a square closing bracket after.[apple] , has square brackets before and after.
I do not want replacements to occur in any other situation.
I tried using the following code:
a="apple" b="fruit" sed -i "s/ $a / $b /g" ./file sed -i "s/\[$a /\[$b /g" ./file sed -i "s/ $a\]/ $b\]/g" ./file sed -i "s/\[$a\]/\[$b\]/g" ./file
I thought that the āgā option at the end would mean that it would replace all instances, but I found that this is not a complete solution. E.g. if file contains the following:
apple spider apple apple spider tree apple tree
The third appearance of the "apple" is not replaced. Also in this several variants of the word are not changed:
apple spider apple apple apple apple apple spider tree apple tree
I suspect this is due to a common "space".
How can I get this to find and replace all instances of $a with $b , regardless of any match?
source share