Small Help on SED

Hi All,
I have come across a command

echo "123 abc" | sed 's/[0-9]*/& &/'

output is

123 123 abc

then i tried in different ways to get 123 abc abc as output.

Can u please explain me the importance of & in the above command.

Thank you

  • Chanakya

This is from the sed man page:

                  An ampersand (&) appearing in the  replacement
                  will  be  replaced  by the string matching the
                  RE.

This means that the sed will replace & with 123 (the string that matches the regular expression in this example). Since the & occurs twice, it is placed there twice.

Thank you blowtorch ..
Expecting the same i tried

echo 123 abc | sed 's/*[a-z]/& &/' to get 123 abc abc as output but i could not ..can u guide me how to get the desired output

try this:

echo 123 abc | sed 's/\([a-z].*\)/& &/'

Try this :

echo "123 abc" | sed 's/[a-z]\{1,\}/& &/'

Another example of sed :

echo "++++ 123 abc ----" | sed 's/\([0-9]\{1,\}\)[[:space:]]*\([a-z]\{1,\}\)/Number=\1 Text=\2/'

Output:
++++ Number=123 Text=abc ----

Jean-Pierre.

hi aigles,
thank you.. I got the required output. Can u explain me what is wrong in

echo 123 abc | sed 's/\([a-z].*\)/& &/' and if possible explain ur command also echo "123 abc" | sed 's/[a-z]\{1,\}/& &/'

-Chanakya

The regex [a-z].* matches one alphabetic character and all following characters.
For example, the command :

echo 123 abc 456 | sed 's/\([a-z].*\)/& &/'

gives the ouput:

123 abc 456 abc 456
echo "123 abc" | sed 's/[a-z]\{1,\}/& &/'

The regex [a-z]\{1,\} matches one or more alphabtic character.
Some commands accept the following syntax [a-z]+

Jean-Pierre.

thank you aigles .. i got it