Finding and replacing text in multiple files from BASHPosted: March 28, 2018
A problem I’ve had lately has been how to find and replace text in multiple files from the command line. Since I keep googling the answer, here’s a post to remind me. It is based on this page: https://superuser.com/questions/428493/how-can-i-do-a-recursive-find-and-replace-from-the-command-line
find . -type f -name "*.txt" -print0 | xargs -0 sed -i'' -e 's/foo/bar/g'
Note that unlike the source, I have
-i'' rather than
-i ''. This seems to required on a *nixes.
I also discovered (mostly ‘cause I’m not good at regular expressions, I suspect), that if you are searching and adding things in < and > that you need to escape everything except the first and the last < and >. So to replace
<head profile="http://dublincore.org/documents/dcq-html"> <meta name="viewport" content="width=device-width, initial-scale=1.0"/> you do
find . -type f -name "*.html" -print0 | xargs -0 sed -i'' -e 's/<head profile\=\"http\:\/\/dublincore\.org\/documents\/dcq-html\/\">/ <head profile\=\"http\:\/\/dublincore\.org\/documents\/dcq-html\/\"\> \<meta name\=\"viewport\" content\=\"width\=device\-width\, initial\-scale\=1\.0\"\/>/g'