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
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.
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.
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).
Use the -i
option of sed
to make the changes in place:
sed -i "s/$OLD/$NEW/g" "$f"
^^
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With