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

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



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.

  • 1
    sed doesn't do "wildcards", it does regular expressions. they are very different (see unix.stackexchange.com/questions/57957/…). 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 1:04
sed -E 's/" rel="lightbox\[[0-9]+\]" title="/#/g' filename
| improve this answer | |
  • 1
    gnu sed also knows -E – don_crissti Apr 10 '16 at 22:03
  • @don_crissti You're right, -E works although strangely it's not listed in my GNU sed man page. – Guido Apr 10 '16 at 22:10
  • 1
    Yeah... I kept meaning to report the fact it's missing from the manual/info page... I'll prolly do it next week. – don_crissti Apr 10 '16 at 22:19

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”.


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.

| improve this answer | |

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.

| improve this answer | |

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

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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