CLI Replace String Recursively by Grep, Xargs and Sed
From WikiMLT
0. Define the searched string and the replacement.
SEARCHED_STR="spas.z.spasov@email.com"
REPLACEMENT="spas.z.spasov@new-email.com"
1. Find the files that should be manipulated.
grep -rni "$SEARCHED_STR"
grep options:
-r,–recursivelike–directories=recurse– with this option, if we do not supply filename or directory grep will operate on al files and directories (and their content) within the current directory.-n,–line-number– print line number with output lines.-i,–ignore-case– ignore case distinctions in patterns and data
2. Test what the result will be.
grep -rliZ "$SEARCHED_STR" | xargs -0 sed "s/${SEARCHED_STR}/${REPLACEMENT}/" | grep -i "$REPLACEMENT"
grep options:
-l,–files-with-matches– print only names of FILEs with selected lines,-Z,–null– use null delimiter – print 0 byte after FILE name.
xargs options:
-0,–null– use null delimiter – items are separated by a null, not whitespace.- One may want to add also the option:
-r,–no-run-if-empty– if there are no arguments, then do not run COMMAND.
sed commands:
s/searched/replacement/– substitute the searched regular expression (or string) with the replacement string – one may need to append thegflag (i.e.s/searched/replacement/g) at the end of the command in order to repeat the command to the end of each line.
3. Perform the actual substitution.
grep -rliZ "$SEARCHED_STR" | xargs -0 sed "s/${SEARCHED_STR}/${REPLACEMENT}/" -i.bak
sed options:
-i[SUFFIX],–in-place[=SUFFIX]– edit files in place (makes backup if SUFFIX supplied), if the suffix is omitted (i.e.-i) no backup file will be created.