1

I have a text file and want to use sed to replace the following string (including the "s):

" rel="lightbox[1846]" title="

with

#

The numbers between [ and ] are variable and change.

I want to include the " in the substitution.

I've been reading up on wildcards and think . will help in some way — different from * wildcards I am used to.

Rui F Ribeiro
  • 56,709
  • 26
  • 150
  • 232
  • 1
    sed doesn't do "wildcards", it does regular expressions. they are very different (see http://unix.stackexchange.com/questions/57957/how-do-regular-expressions-differ-from-wildcards-used-to-filter-files). Also, it looks like you're trying to parse/edit HTML or XML. Don't use sed (or any other regex based tool), use an XML or HTML parser instead. – cas Apr 10 '16 at 01:04

4 Answers4

2
sed -E 's/" rel="lightbox\[[0-9]+\]" title="/#/g' filename
Guido
  • 4,114
0

sed is indeed the right tool for this job, with its s command (the one that's used the most).

Wildcards for file names in the shell, and regular expressions in tools such as grep and sed, have a different syntax. See Why does my regular expression work in X but not in Y? for a summary of the differences.

In the text to replace, [ is a regular expression special character; the other characters stand for themselves. Since it's a special character, it needs to be written as \[ (the backslash makes the next character stand for itself instead of having its special meaning).

A sequence of digits is [0-9]*: [0-9] means “any digit”, and * means “repeat the preceding character or character set 0 or more times”.

Thus:

sed 's/" rel="lightbox\[[0-9]]" title="/#/' <old-file >new-file

The single quotes make the shell pass everything in between literally to the sed command.

0

How about:

sed 's/^" rel=.*title="/#/g' filename

This makes use of the . and the * you referenced in your question to match characters in the middle of the string which can be variable. Tested and know to achieve the required result you specified.

Although I just used a small sample of text from the beginning and ending of the string, you could be more precise if there was a chance of inadvertently matching an unwanted string.

F1Linux
  • 2,476
-1

sed 's/" rel="lightbox[[0-9]+]" title="/#/g' filename

But if you wanna use it in perl , you have to use it like below

`sed 's/" rel="lightbox\[[0-9]+\]" title="/#/g' filename

Mudassar Rana
  • 27
  • 1
  • 3