-2

I want to update a string on several text files from command line (bash).

Cyrus
  • 84,225
  • 14
  • 89
  • 153
oml
  • 115
  • 2
  • 8

1 Answers1

-1

To update string to 'John' only script text files (*.sh) containing the searched string 'Peter' and make backup first (.bak):

¡¡DON'T USE!!

$ sed -i.bak 's/Peter/John/g' $(find bin/ -type f -name '*.sh' \-exec grep -l Peter {} +)

Thanks for your comments Jetchisel and Ed Morton

After research I found this solution (\b is for word limit if you only want to change words):

$ STRING_OLD="\bPeter\b"; STRING_NEW="John"; find bin/ -type f -name '*.sh' -not -name "*.bak" -print0 | xargs -0 grep -Zl "$STRING_OLD" | xargs -t -0 sed -i.bak 's/'"$STRING_OLD"'/'"$STRING_NEW"'/g'

It works with filenames/directories with spaces,tabs,new lines and non ASCII chars.

Variable STRING_OLD is a regexp for sed s/regexp/replacement/ command. You must aware of it.

You also see changed files. It only changes (and backs up) in files where STRING_OLD is found in regexp. The rest of the files remain untouched (that's what I wanted).

oml
  • 115
  • 2
  • 8
  • That breaks if the file/directory name contains spaces/tabs and new lines.... – Jetchisel May 29 '23 at 11:28
  • ... or if the search string contains regexp metachars or a string that can be a substring of another, or the replacement string contains backreference metachars... – Ed Morton May 29 '23 at 11:32