2

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?

8
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.

  • Thanks it worked. Key i was missing was to put memorized pattern in parentheses. – Javanator Jul 17 '15 at 8:51
3
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
3

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).

2

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

     awk -F "=" '{print $1"("$2")="$2}' file

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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