Finding and replacing text in multiple files from BASH

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:

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=""> 


<head profile="">
<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'



Get every new post delivered to your Inbox

Join other followers: