Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

I have a file with text as

Afghanistan=+93
Albania=+355
Algeria=+213
American Samoa=+1
Andorra=+376
Angola=+244

It has all the country list and its dialing code.

I want to replace:

Afghanistan=+93 with Afghanistan(+93)=+93

I can get the selection pattern as =\+[0-9]*, but what will be replacement pattern string?

I know of \1 that is the captured match for selection but it don't seem to work for sed. So the regex needs to have selection.

How can I do that using sed or any other unix tools?

share|improve this question

4 Answers 4

up vote 8 down vote accepted
sed 's/=\(+[0-9]\{1,3\}\)/(\1)=\1/' 

To address your problem (as I understood):

Patterns that need to be memorized in sed are to be enclosed in parentheses - their appearance defines their index number. E.g.:

sed 's/\(<memorized_pattern_1>\)<not_memorized>\(<memorized_pattern_2>\)/\2\1/'

would swap patterns 1 and 2 and delete the middle one.

share|improve this answer
    
Thanks it worked. Key i was missing was to put memorized pattern in parentheses. –  Javanator Jul 17 at 8:51
sed 's/=\([^= ]*\) *$/(\1)&/' <in >out

The above will just replace the last equals sign on a line and all characters which follow first with...

  1. A copy of those that follow and which are not space surrounded by two parens (in case there are any trailing spaces on a line)

  2. The whole matched pattern all over again.

On the right-hand-side (the replacement field of the s///ubstitution) \1 represents the first \( grouped capture \) and & represents the entire matched pattern as a group. And so...

sed 's/=\([^= ]*\) *$/(\1)&/' <<\IN
    Afghanistan=+93
    Albania=+355
    Algeria=+213
    American Samoa=+1
    Andorra=+376
    Angola=+244
IN

    Afghanistan(+93)=+93
    Albania(+355)=+355
    Algeria(+213)=+213
    American Samoa(+1)=+1
    Andorra(+376)=+376
    Angola(+244)=+244
share|improve this answer
    
Thanks for the answer –  Javanator Jul 17 at 9:09

Use that:

sed 's/=\(+[0-9]\+\)/(\1)=\1/' file

It searches for =+ followed by at least one digit ([0-9]\+) and replaces all with the desired format ((\1)=\1).

share|improve this answer
    
Thanks for the answer –  Javanator Jul 17 at 9:09

Suppose all the data is there in a file named as file, then

     awk -F "=" '{print $1"("$2")="$2}' file
share|improve this answer
    
Thanks for the answer –  Javanator Jul 17 at 9:09

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.