Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find and replace string in a file

I'm trying to find and replace a string in a folder of files.

Could someone possibly help me?

My script is as follows:

#!/bin/bash
OLD="This is a"
NEW="I am a"
DPATH="/home/user/test/*.txt"
BPATH="/home/user/test/backup/foo"
[ ! -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"
   else
    echo "Error: Cannot read $f"
  fi
done

Now this seems to find the string 'This is a' and replaces with 'I am a', but this only prints to screen.

I need it to replace in the files themselves.

Thanks

like image 431
terrid25 Avatar asked Dec 14 '10 09:12

terrid25


People also ask

How do I find and replace text in multiple files?

Remove all the files you don't want to edit by selecting them and pressing DEL, then right-click the remaining files and choose Open all. Now go to Search > Replace or press CTRL+H, which will launch the Replace menu. Here you'll find an option to Replace All in All Opened Documents.

How do I replace a string in a python file?

To replace text in a file we are going to open the file in read-only using the open() function. Then we will t=read and replace the content in the text file using the read() and replace() functions.

How do I find and replace in all files?

Not only can you search the current open file in the editor, but also all open documents, the entire solution, the current project, and selected folder sets. You can also search by file name extension. To access the Find/Replace in Files dialog box, select Find and Replace on the Edit menu (or press Ctrl+Shift+F).


2 Answers

Use the -i option of sed to make the changes in place:

sed -i "s/$OLD/$NEW/g" "$f"
    ^^
like image 158
codaddict Avatar answered Oct 21 '22 08:10

codaddict


The output goes to screen (stdout) because of the following:

sed "s/$OLD/$NEW/g" "$f"

Try redirecting to a file (the following redirects to a new files and then renames it to overwrite the original file):

sed "s/$OLD/$NEW/g" "$f" > "$f.new" && mv "$f.new" "$f"
like image 32
NPE Avatar answered Oct 21 '22 08:10

NPE