About Linux FAQ

Browse More FAQs:

Bash Shell: Replace a string with another string in all files using sed and perl -pie

Posted by Vivek on Tuesday November 27, 07 @6:32 pm

Q. How do I replace a string with another string in all files? For example, ~/foo directory has 100s of text file and I'd like to find out xyz string and replace with abc. I'd like to use sed or any other tool to replace all occurrence of the word.

A.sed command is designed for this kind of work i.e. replace strings.

sed replace word / string syntax

sed -i 's/old-word/new-word/g' *.txt

GNU sed command can edit files in place (makes backup if extension supplied) using -i option. If you are using old or UNIX sed command try the following syntax:

sed 's/old/new/g' input.txt > output.txt

I recommend using old syntax along with for loop:

#!/bin/bash
OLD="xyz"
NEW="abc"
DPATH="/home/you/foo/*.txt"
BPATH="/home/you/bakup/foo"
TFILE="/tmp/out.tmp.$$"
[ ! -d $BPATH ] && mkdir -p $BPATH || :
for f in $DPATH
do
  if [ -f $f -a -r $f ]; then
    /bin/cp -f $f $BPATH
   sed "s/$OLD/$NEW/g" "$f" > $TFILE && mv $TFILE "$f"
  else
   echo "Error: Cannot read $f"
  fi
done
/bin/rm $TFILE

perl -pie trick

perl -pie 's/old-word/new-word/g' input > output

Subscribe to our free e-mail newsletter or RSS feed to get all updates. You can Email this page to a friend.

Related Linux / UNIX FAQ:

Discussion on This FAQ

  1. Jeff Schroeder Says:

    Ravi,

    Glancing at this I see a typo:
    sed “s/$OLD/$NEW/g” “$f” > $TFILE && mv TFILE “$f”

    Should be:
    sed “s/$OLD/$NEW/g” “$f” > $TFILE && mv $TFILE “$f”

    Also, you didn’t seem to mention that sed can auto-create backup files using syntax like this:
    sed -i.bak ’s/old-word/new-word/g’ filename.txt

    That will edit filename.txt and copy the original to filename.txt.bak

  2. vivek Says:

    Jeff,

    thanks for the heads up!

  3. Bhargav Says:

    Hi,

    I don’t know normal sed has -i.bak option but perl provides the backup of the original file.

    perl -p -i.bak -e ’s/AAA/aaa/’ file_name

Leave a Reply

We encourage your comments, and suggestions. But please stay on topic, be polite, and avoid spam. Please do not use the comment form to ask for help / question. Ask your question on the excellent Linux tech support forum. Thank you very much for stopping by our site!

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

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word

Tags: , , , , , , , , ~ Last updated on: November 27, 2007

Copyright © 2006-2008 nixCraft. All rights reserved - TOS/Disclaimer - Privacy policy - Sitemap - Powered by Open source software.