How to find and replace a string with spaces and / recursively?

Hi all,

I wanted to find and replace an email id from entire directory structure on a Linux server. I found that

find . -type f -print0 | xargs -0 sed -i 's/abc@yahoo.com/xyz@gmail.com/g'

would do it perfectly.

But my search criteria has extended and now I want to search for a string1 like "/dir1/dir2/dir3/file1 -- -k abc@yahoo.com" and replace it with string2 which will be like "/dirA/dirB/dirC/fileD -- -j xyz@gmail.com"
And I want to do it recursively on entire directory structure, say under my home directory /home/usr1. So I should be able to search for string1 in all the files in directory and sub directories of /home/usr1 and replace it with string2.

I had tried something foolish which I knew is not going to work:

find . -type f -print0 | xargs -0 sed -i 's/"/dir1/dir2/dir3/file1 -- -k abc@yahoo.com"/"/dirA/dirB/dirC/fileD -- -j xyz@gmail.com"/g

And as expected it didn't work and shows error as:

sed: -e expression #1, char 10: unknown option to `s'

Please let me know if there is a way to do this on UNIX/Linux (or even using Perl)

Thanks in advance.

You can see that sed is unable to understand where to look for replacement string as there are many "/" chars.
Good news is you can use any other character as the delimiter if your string contains "/".

sed -i 's|/dir1/dir2/dir3/file1 -- -k abc@yahoo.com|/dirA/dirB/dirC/fileD -- -j  xyz@gmail.com|g'

Remember you also doesn't have closing single quote in your code.

1 Like

Thanks a lot clx for your suggestion. It worked perfectly.