sed question

I ran into this tutorial code that I don't understand.

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

the only change is a space in front.

isn't the matching string "123", and the output would therefore be
abc 123 123

?
bhomassAsked:
Who is Participating?
 
tel2Connect With a Mentor Commented:
Hi bhomass,

The [0-9]* matches the beginning of the input (before the "a"), because there are 0 (or more) digits there.

"&" is that entire (empty) match, so "& &" just prints a space (the space between the 2 empty strings), which prints before your input of "abc 123", which was not changed by the substitution.  (Are you falling for this?  I'm just making it up as I go along.)

Perl does the same thing:
    echo "abc 123" | perl -pe 's/[0-9]*/$& $&/'
The output is: " abc 123"
0
 
farzanjCommented:
Try this:
 echo "abc 123" | sed 's/[0-9][0-9]*/& &/'

Difference is 1 or more instead of 0 or more.
0
 
bhomassAuthor Commented:
I am not trying to get anything. just want to understand how the command got that result.
0
 
Gerwin Jansen, EE MVETopic Advisor Commented:
Minor addition: the subsitute command replaces only once ( &/ ) and since the first match is at the beginning of the line, you will see the space there.

If you want to match exactly 3 numbers, you can do this:

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

and it would return your match (123), a space and your match (123) again so:

abc 123 123
0
 
bhomassAuthor Commented:
ha, that's tricky. got me that time. not every time, but this time for sure.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.