13

I have file with these lines

G8 = P(G1,G3)
G9 = P(G3,G4)
G12 = P(G2,G9)
G15 = P(G9,G5)
G16 = P(G8,G12)
G17 = P(G12,G15)

I need the output as

G1,G3
G3,G4
.....

How can I do it with sed/grep command or using perl?

15

A few other ways:

  • sed

    sed 's/.*(\(.*\))/\1/' file 
    
  • perl

    perl -pe 's/.*\((.*)\)/$1/' file 
    

    or

    perl -lanF"[()]" -e 'print $F[1]' file 
    

    or

    perl -pe 's/.*\((.+?)\).*/$1/;' file 
    
  • awk

    awk -F"[()]" '{print $2}' file 
    
  • shell

    while IFS="()" read a b; do echo "$b"; done < file 
    
  • would you tell more about how awk method works ?, its easy to remember too – satch_boogie Aug 19 '17 at 17:52
  • 1
    @satch_boogie the -F lets you chose what character(s) awk will use to split the line into fields. Here, I am giving it a character class ([]) consisting of opening and closing parentheses. So it will split the line on ( and on ). As a result, the 2nd field will be the contents of the parentheses. E.g, with the string G8 = P(G1,G3)foo, $1 will be G8 = P, $2 will be G1,G3 and $3 would be foo. – terdon Aug 22 '17 at 15:24
7

There is more than one way to do it:

perl -nle 'print $1 if /\((.*)\)/' file

or:

awk 'NR > 1 {print $1}' RS='(' FS=')' file
5
grep -oP '\(\K[^)]+' file

That looks for the opening parenthesis, ignores it, then prints all the non-close-parenthesis characters that follow.

Requires GNU grep

5

sed 's/^.*(//;s/)$//' /path/to/file

To break this down:

sed is the stream editor. 's/^.*(//;s/)$//' is the script being sent to sed, which breaks down as the following:

s/^.*(//    substitute nothing for the beginning of any line (`^`) followed by anything up until an open-paren (`(`)
s/)$//      substitute nothing for a close-paren (`)`) followed immediately by the end of a line
1

A simple cut solution:

$ cat test01 |cut -d "(" -f2 | cut -d ")" -f1

0
awk -F'(' '{print $NF}' file | sed 's/)//g'

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.