Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sed: replace a specific part

Tags:

linux

bash

sed

I need to replace a specific part of a link

for example:

http://sub.somedomain.com/s/be2b46b4cb28ed64fe59d191cb600117/2013/image.jpg

to

http://sub.somedomain.com/s/123123/2013/image.jpg

what I've tried:

echo "http://sub.somedomain.com/s/be2b46b4cb28ed64fe59d191cb600117/2013/image.jpg" | sed "s@/s/(.+?)/@123123@g"
like image 846
Orlo Avatar asked Dec 25 '13 21:12

Orlo


People also ask

How do you replace part of a string in Linux?

To replace a substring with new value in a string in Bash Script, we can use sed command. sed stands for stream editor and can be used for find and replace operation. We can specify to sed command whether to replace the first occurrence or all occurrences of the substring in the string.

How do you escape special characters in sed?

Put a backslash before $. */[\]^ and only those characters (but not inside bracket expressions).

Does sed use regex?

Regular expressions are used by several different Unix commands, including ed, sed, awk, grep, and to a more limited extent, vi.


1 Answers

sed "s@/s/[^/]*/@/s/123123/@g"

Problems with your regex:

  • brackets ( and ) are regular characters in basic regular expressions (BRE) (and they are not really needed here)
  • + is also not special in BRE
  • if you enabled extended regexes with sed -E, you would match too much because you don't stop at the next slash
like image 93
ales_t Avatar answered Sep 25 '22 05:09

ales_t