Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find and Replace string in all files recursive using grep and sed [duplicate]

I'm getting a

sed: -e expression #1, char 22: unterminated `s' command  

is there a problem on my script? Also the "oldstring" has special characters

#!bin/bash oldstring='<script>"[oldscript]"</script>' newstring='<script>"[newscript]"</script>' grep -rl $oldstring /path/to/folder | xargs sed -i s/$oldstring/$newstring/g 
like image 809
jmazaredo Avatar asked Apr 10 '13 08:04

jmazaredo


People also ask

How do I use sed to find and replace text in a file?

Find and replace text within a file using sed command Use Stream EDitor (sed) as follows: sed -i 's/old-text/new-text/g' input.txt. The s is the substitute command of sed for find and replace.

Can I use grep and sed together?

This collection of sed and grep use cases might help you better understand how these commands can be used in Linux. Tools like sed (stream editor) and grep (global regular expression print) are powerful ways to save time and make your work faster.

How do you grep and replace?

On OS X you will need to change sed -i 's/str1/str2/g' to sed -i "" 's/str1/str2/g' for this to work. @cmevoli with this method, grep goes through all the files and sed only scans the files matched by grep .


1 Answers

As @Didier said, you can change your delimiter to something other than /:

grep -rl $oldstring /path/to/folder | xargs sed -i s@$oldstring@$newstring@g 
like image 181
wudeng Avatar answered Sep 18 '22 17:09

wudeng