Home > front end >  Using find/sed to replace strings in text files- works only on some of the matches
Using find/sed to replace strings in text files- works only on some of the matches

Time:08-24

I want to replace

{not STRING }

with

(not STRING )

I ran

find . -maxdepth 1 -type f -exec sed -i -E 's/{not\s([^\s}] )\s}/(not \1 )/g' {} ;

It worked on some of the matches. When I run grep with the same pattern it shows more files that still have STRING. Ran find/sed again, same result.

CodePudding user response:

You need to escape curly braces ({}), as they are regex meta-characters. Also \s is not POSIX sed, I would use the more portable [[:space:]].

Your code did not work on the example text for me (GNU/Linux). This does:

sed -E 's/\{not[[:space:]] ([^[:space:]}] )[[:space:]] \}/(not \1 )/g'

I also allowed for variable length whitespace directly after not and directly before } (using [[:space:]] ). You may or may not want that.

Also:

  • On MacOS sed I believe you need to supply a suffix argument to -i.
  • The trailing ; for find -exec must be quoted (\;) to avoid interpretation by the shell.

So the command would be:

find . -maxdepth 1 -type f -exec \
sed -E -i .TMP 's/\{not[[:space:]] ([^[:space:]}] )[[:space:]] \}/(not \1 )/g' {} \;

If .TMP conflicts with an existing file, choose a different suffix.

  • Related