sed snippets

Appending after a pattern from a file in sed

Tagged sed, linux, bash  Languages bash

Useful when you want to append the contents of a whole file into something you are sed'ing. Be careful if you use -i, it will replace the working file.

sed -i "/attr_accessor :config/r ../patch_for_application.rb.tmpl" app/controllers/application.rb

How to remove text between a tag from XML or HTML with SED

Tagged sed, html, xml, xmlstarlet  Languages bash

This will remove the users tag and everything in between the users tag:

sed -i .bak '/<users type="array">/,/<\/users>/d' users.xml

A backup will be created named users.xml.bak.

If you want to select only specific tags use this:

sed -n -e '/<private-parts>/,/<\/private-parts>/p' e users.xml

For more advanced XML processing use: * XMLStarlet * xml-coreutiles * xml2/2xml * Your imagination.

Recursive find and replace on OSX/Linux

Tagged search, replace, sed, osx  Languages bash

NOTE: remember to exclude the .git folder…

Search and replace XXX with YYY in all files:

perl -e "s/XXX/YYY/g;" -pi $(find . -type f)


If you get this error:

zsh: argument list too long: perl

Your argument list is clearly too long. Try this instead, or use xargs:

find . \
   -type f \
   -exec perl -i -pe's/XXX/YYY/g' {} +

Search and Replace with Sed

Using sed is more complicated, but this should at least work on Linux:

# Find, backup and replace
find . -name "*.rb" -print | xargs sed -i.bak 's/XXX/YYY/g'
# Delete backup files
find . -name '*.bak' -type f -delete


Also see: