Bash Shell: Replace a string with another string in all files using sed and perl -pie
Posted by adminAug 27
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
One comment
You must be logged in to post a comment.