Easy Search and Replace in Multiple Files on Linux Command Line

7 maggio 2009 - Fonte: http://blog.morphey.org Lascia il tuo commento »
E' la tua prima volta qui? Allora iscriviti GRATIS ai nostri feeds! 

I recently came across a typo that existed in a bunch of html files on my web server. I thought it should be easy enough to change, but since it was in a number of files, editing it by hand would be time consuming. Fortunately, there is an easy, one liner command to replace the text in multiple files in a sub directory using recursion.

grep -lr -e '<oldword>' * | xargs sed -i 's/<oldword>/<newword>/g'

This command broken down:

  • grep for the word in a files, use recursion (to find files in sub directories), and list only file matches
  • | xargs passes the results from the grep command to sed
  • sed -i uses a regular expression (regex) to evaluate the change: s (search) / search word / target word / g (global replace)

For more information, see man pages for grep, sed, and xarg. Also it is very handy to learn about regular expressions as they are a valuable tool to any command line programmer!

...

Leggi il seguito »






SEGNALA / INVIA QUESTO POST:  Share
Hai trovato questo articolo interessante? Iscriviti GRATIS ai nostri feeds! 

Lascia un Commento