Reverse detail from Kakelbont MS 1, a fifteenth-century French Psalter. This image is in the public domain. Daniel Paul O'Donnell

Forward to Navigation

Finding and replacing text in multiple files from BASH

Posted: Mar 28, 2018 17:03;
Last Modified: Mar 28, 2018 17:03
Keywords:

---

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

with

<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'
----  

Comment

:
:

:

Textile help

Back to content

Search my site

Sections

Current teaching

Recent changes to this site

Tags

anglo-saxon studies, caedmon, citation practice, composition, computers, digital humanities, digital pedagogy, grammar, history, moodle, old english, pedagogy, research, students, study tips, teaching, tips, tutorials, unessay, universities

See all...

Follow me on Twitter