CLI Replace String Recursively by Grep, Xargs and Sed

From WikiMLT

0. De­fine the searched string and the re­place­ment.

SEARCHED_STR="spas.z.spasov@email.com"
REPLACEMENT="spas.z.spasov@new-email.com"

1. Find the files that should be ma­nip­u­lat­ed.

grep -rni "$SEARCHED_STR"

grep op­tions:

  • -r, –re­cur­sive like –directories=recurse – with this op­tion, if we do not sup­ply file­name or di­rec­to­ry grep will op­er­ate on al files and di­rec­to­ries (and their con­tent) with­in the cur­rent di­rec­to­ry.
  • -n, –line-num­ber – print line num­ber with out­put lines.
  • -i, –ig­nore-case – ig­nore case dis­tinc­tions in pat­terns and da­ta

2. Test what the re­sult will be.

grep -rliZ "$SEARCHED_STR" | xargs -0 sed "s/${SEARCHED_STR}/${REPLACEMENT}/" | grep -i "$REPLACEMENT"

grep op­tions:

  • -l, –files-with-match­es – print on­ly names of FILEs with se­lect­ed lines,
  • -Z, –null – use null de­lim­iter – print 0 byte af­ter FILE name.

xargs op­tions:

  • -0, –null – use null de­lim­iter – items are sep­a­rat­ed by a null, not white­space.
  • One may want to add al­so the op­tion: -r, –no-run-if-emp­ty – if there are no ar­gu­ments, then do not run COM­MAND.

sed com­mands:

  • s/​​​searched/​​​replacement/​​​ – sub­sti­tute the searched reg­u­lar ex­pres­sion (or string) with the re­place­ment string – one may need to ap­pend the g flag (i.e. s/​​​searched/​​​replacement/​​​g) at the end of the com­mand in or­der to re­peat the com­mand to the end of each line.

3. Per­form the ac­tu­al sub­sti­tu­tion.

grep -rliZ "$SEARCHED_STR" | xargs -0 sed "s/${SEARCHED_STR}/${REPLACEMENT}/" -i.bak

sed op­tions:

  • -i[SUFFIX], –in-place[=SUFFIX] – ed­it files in place (makes back­up if SUF­FIX sup­plied), if the suf­fix is omit­ted (i.e. -i) no back­up file will be cre­at­ed.