-2

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

0

1 Answer 1

-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).

Sign up to request clarification or add additional context in comments.

2 Comments

That breaks if the file/directory name contains spaces/tabs and new lines....
... 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...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.