Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find and replace items not preceded or followed by specific characters with sed?

Tags:

bash

replace

sed

How can I restrict find and replace to replace items, but not if the character immediately before it is "A", "B", or "C" or the character immediately after it is "X", "Y", or "Z". E.g. given these input lines, if "cat" is to be replaced with replaced with "pet":

  • "There is a cat." → "These is a pet."
  • "There is Acat." is unchanged, because "A' is found before.
  • "There is catY." is unchanged, because "Y' is found after.
  • "There is CcatX." is unchanged, because "C' is found before and "X" after.
like image 737
Village Avatar asked Nov 17 '13 04:11

Village


People also ask

How do you use sed to replace the first occurrence in a file?

With GNU sed's -z option you could process the whole file as if it was only one line. That way a s/…/…/ would only replace the first match in the whole file. Remember: s/…/…/ only replaces the first match in each line, but with the -z option sed treats the whole file as a single line.


1 Answers

This sed should work for you:

sed -r 's/(^|[^ABC])cat\>/\1pet/g; s/\<cat([^XYZ]|$)/pet\1/g' file

Testing:

sed -r 's/(^|[^ABC])cat\>/\1pet/g; s/\<cat([^XYZ]|$)/pet\1/g' <<< 'cat is a cat is a cat'
pet is a pet is a pet
like image 155
anubhava Avatar answered Oct 04 '22 19:10

anubhava