80

I'm attempting to use SED through OS X Terminal to perform a find and replace.

Imagine I have this string littered throughout the text file: http://www.find.com/page

And I want to replace it with this string: http://www.replace.com/page

I'm having trouble because I'm not sure how to properly escape or use the "/" character in my strings. For example if I simply wanted to find "cat" and replace with "dog" I've found the following command that works perfectly:

sed -i '' 's/cat/dog/g' file.txt

Does anyone have any ideas on how to achieve the same functionality only instead of cat and dog have strings or URLs that container the "/" character? I tried many different ways of escaping the "/" characters but then it seems as if SED can no longer "find" the string and it doesn't perform any find & replace actions.

Any help or tips are greatly appreciated.

Thanks!

0

2 Answers 2

227

/ is not the delimiter in sed commands, it's just one of the possible ones. For this example, you can for example use , instead since it does not conflict with your strings;

echo 'I think http://www.find.com/page is my favorite' | 
    sed 's,http://www.find.com/page,http://www.replace.com/page,g'
0
52

sed can take whatever follows the "s" as the separator. Since you are working with URL it is a good practice to use a different delimiter other than / to not confuse sed when your substitution ends and replacement begins.

However, having said that you can definitely use / if you wish too. You just need to escape the literal /.

So, you can either do:

sed 's/http:\/\/www.find.com\/page/http:\/\/www.replace.com\/page/g' input_file

or use a different delimiter to avoid making your cryptic sed more cryptic.

sed 's#http://www.find.com/page#http://www.replace.com/page#g' input_file
3
  • Using this approach, any reason why the following only outputs the file without any changes? sed 's#:0.0.1#:new-build-number#g' some.yaml. 1. The change does not occur. 2. I don't want the file printed, just updated.
    – Idan Adar
    Apr 26, 2017 at 4:14
  • 4
    The space character works well as a sed delimiter when processing URLs. It's visually clean and will never occur in a properly-formatted (i.e., escaped) URL. Jun 27, 2019 at 23:40
  • 1
    I had to use sed -i to make it work. Why doesn't it work without the -i? I read that -i[SUFFIX], --in-place[=SUFFIX] edit files in place (makes backup if SUFFIX supplied) What does it mean that it makes backup?
    – Vasiliki
    Feb 9, 2021 at 12:53

Not the answer you're looking for? Browse other questions tagged or ask your own question.