sed question

Posted on 2012-09-06
Medium Priority
Last Modified: 2012-09-06
I ran into this tutorial code that I don't understand.

echo "abc 123" | sed 's/[0-9]*/& &/'
 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

Question by:bhomass
LVL 31

Expert Comment

ID: 38373801
Try this:
 echo "abc 123" | sed 's/[0-9][0-9]*/& &/'

Difference is 1 or more instead of 0 or more.

Author Comment

ID: 38374170
I am not trying to get anything. just want to understand how the command got that result.
LVL 12

Accepted Solution

tel2 earned 600 total points
ID: 38374218
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"
LVL 38

Expert Comment

by:Gerwin Jansen, EE MVE
ID: 38374331
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

Author Comment

ID: 38374464
ha, that's tricky. got me that time. not every time, but this time for sure.

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

It’s 2016. Password authentication should be dead — or at least close to dying. But, unfortunately, it has not traversed Quagga stage yet. Using password authentication is like laundering hotel guest linens with a washboard — it’s Passé.
In part one, we reviewed the prerequisites required for installing SQL Server vNext. In this part we will explore how to install Microsoft's SQL Server on Ubuntu 16.04.
Learn several ways to interact with files and get file information from the bash shell. ls lists the contents of a directory: Using the -a flag displays hidden files: Using the -l flag formats the output in a long list: The file command gives us mor…
Connecting to an Amazon Linux EC2 Instance from Windows Using PuTTY.
Suggested Courses
Course of the Month13 days, 14 hours left to enroll

807 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question