Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace a character within a matched pattern using ampersand (&)

When we match a pattern using sed, the matched pattern is stored in the "ampersand" (&) variable. IS there a way to replace a character in this matched pattern using the ampersand itself ?

For example, if & contains the string "apple1", how can I use & to make the string to "apple2" (i.e replace 1 by 2) ?

like image 308
user1418321 Avatar asked Oct 02 '12 16:10

user1418321


People also ask

How do you replace some text pattern with another text pattern in a file?

`sed` command is one of the ways to do replacement task. This command can be used to replace text in a string or a file by using a different pattern.

How do you use ampersand in sed?

To insert an actual ampersand in the replacement text, use \& .

What does ampersand mean in sed?

Turns out that the ampersand (&) has a special meaning in sed and is, in this case, being used to "append characters after found element". Practical example: # cat /tmp/xxx.html | sed "s/text/& I wrote myself/g" This is a text I wrote myself containing an ö umlaut. Because in German we use ä ö ü.

How do you escape and sed?

\& works for me. For example, I can replace all instances of amp with & by using sed "s/amp/\&/g" . If you're still having problems, you should post a new question with your input string and your code. Yea it does.


2 Answers

If I guessed right, what you want to do is to apply a subsitution in a pattern matched. You can't do that using &. You want to do this instead:

echo apple1 apple3 apple1 apple2 botemo1 | sed '/apple./ { s/apple1/apple2/g; }'

This means that you want to execute the command substitution only on the lines that matches the pattern /apple./.

like image 120
Elias Dorneles Avatar answered Sep 27 '22 16:09

Elias Dorneles


You can also use a capture group. A capture is used to grab a part of the match and save it into an auxiliary variable, that is named numerically in the order that the capture appears.

echo apple1 | sed -e 's/\(a\)\(p*\)\(le\)1/\1\2\32/g'

We used three captures:

  1. The first one, stored in \1, contains an "a"
  2. The second one, stored in \2, contains a sequence of "p"s (in the example it contains "pp")
  3. The third one, stored in \3, contains the sequence "le"

Now we can print the replacement using the matches we captured: \1\2\32. Notice that we are using 3 capture values to generate "apple" and then we append a 2. This wont be interpreted as variable \32 because we can only have a total of 9 captures.

Hope this helps =)

like image 42
Janito Vaqueiro Ferreira Filho Avatar answered Sep 27 '22 18:09

Janito Vaqueiro Ferreira Filho