LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Sed - the repeated pattern (&) (https://www.linuxquestions.org/questions/linux-newbie-8/sed-the-repeated-pattern-and-4175472612/)

anandg111 08-08-2013 05:26 AM

Sed - the repeated pattern (&)
 
can somebody please explain the repeated pattern (&) in sed with propper example.

druuna 08-08-2013 05:47 AM

Quote:

Originally Posted by anandg111 (Post 5005478)
can somebody please explain the repeated pattern (&) in sed with propper example.

The & has nothing to do with repeated patterns.
Quote:

& Replaced by the string matched by the regular expression.
If you use something like this:
Code:

sed 's/foo/&bar/' infile
The & is replaced with the regular expression (foo in this case) in the replace part.
Code:

$ cat infile
foo bar

$ sed 's/foo/&bar/' infile
foobar bar

The above can be rewritten as:
Code:

sed 's/foo/foobar/' infile
Here's another example using a regular expression:
Code:

$ cat infile
foo bar

$ sed 's/.*/& foobar/' infile
foo bar foobar

The above can also be written as (there are probably more ways):
Code:

sed 's/foo bar/foo bar foobar/' infile

or

sed 's/$/ foobar/' infile


colucix 08-08-2013 05:51 AM

& is substituted by the matched string. It's useful when you want to preserve the string matched by a regular expression, but you don't know what exactly is a priori. Suppose you want to embed a number in a string within parentheses. If you know what number is it you should do simply:
Code:

$ echo "My birth year is 1968." | sed 's/1968/(1968)/'
My birth year is (1968).

However if you don't know what the number is, you cannot put it in the replacement string. In this case the & pattern is your friend:
Code:

$ echo "My birth year is 1974." | sed 's/[0-9]\+/(&)/'
My birth year is (1974).
$ echo "My birth year is 1935." | sed 's/[0-9]\+/(&)/'
My birth year is (1935).

Basically it is the whole string matched by the regular expression, that you need to repeat in the replacement string without knowing what is it.

Edit: too late! ;)


All times are GMT -5. The time now is 12:15 AM.