Linux Ask!

Linux Ask! is a Q & A web site specific for Linux related questions. Questions are collected, answered and audited by experienced Linux users.

Mar 262009

How to replace multiple strings using sed?


If you have multiple strings to replace, you can either using the "-e" option in sed, e.g.

sed -e 's/a/A/' -e 's/b/B/' < old.txt > new.txt

or, you can use a sed script file to store all the replace conditions

e.g. vi replace.sed


and execute like

sed -f replace.sed < old.txt > new.txt

  5 Responses to “Replace multiple strings using sed”

  1. Or you can include all in a single, newline-separated string:

    sed 's/a/A/g
    s/c/C/g' new.txt

  2. Or

    sed "s/str1/str2/g ; s/strA/strB/g ; s/foo/bar/g" file1 > file2

  3. I was wondering if you could use a single sed s command to replace multiple different strings with one string. In my case I need to replace all punctuation marks with an underscore. I understand I could write multiple sed s commands for ".", "?" and "!". I was just wondering if there was a cleaner way to do it.

    For those who want to know this is for an Applescript for finding and editing iTunes tracks since iTunes automatically changes punctuation in the artist, album, and track name to an "_".

  4. @Mike

    You can use character class, e.g.

    echo "?,." | sed 's/[?,.]/_/g'

  5. thank you so much guys for this different ways of sed usage. @Ian Howarth : your's is apt for my script thank you!

 Leave a Reply



You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>