How to match and cut the string with different conditions using sed?

Viewed 69

I want to grep the string which comes after WORK= and ignore if there comes paranthesis after that string .

The text looks like this :

//INALL TYPE=GH,WORK=HU.ET.ET(IO)
//INA2 WORK=HU.TY.TY(OP),TYPE=KK
//OOPE2 TYPE=KO,WORK=TEXT.LO1.LO2,TEXT
//OOP2 TYPE=KO,WORK=TEST1.TEST2
//H1 WORK=OP.TEE.GHU,TYPE=IU

So, desirable output should print only :

TEXT.L01.L02
TEST1.TEST2
OP.TEE.GHU

So far , I could just match and cut before WORK= but could not remove WORK= itself:

sed -E 's/(.*)(WORK=.*)/\2/'

I am not sure how to continue . Can anyone help please ?

3 Answers

You can use

sed -n '/WORK=.*([^()]*)/!s/.*WORK=\([^,]*\).*/\1/p' file > newfile

Details:

  • -n - suppresses the default line output
  • /WORK=.*([^()]*)/! - if a line contains a WORK= followed with any text and then a (...) substring skips it
  • s/.*WORK=\([^,]*\).*/\1/p - else, takes the line and removes all up to and including WORK=, and then captures into Group 1 any zero or more chars other than a comma, and then remove the rest of the line; p prints the result.

See the sed demo:

s='//INALL TYPE=GH,WORK=HU.ET.ET(IO)
//INA2 WORK=HU.TY.TY(OP),TYPE=KK
//OOPE2 TYPE=KO,WORK=TEXT.LO1.LO2,TEXT
//OOP2 TYPE=KO,WORK=TEST1.TEST2
//H1 WORK=OP.TEE.GHU,TYPE=IU'
sed -n '/WORK=.*([^()]*)/!s/.*WORK=\([^,]*\).*/\1/p' <<< "$s"

Output:

TEXT.LO1.LO2
TEST1.TEST2
OP.TEE.GHU

Could you please try following awk, written and tested with shown samples in GNU awk.

awk '
match($0,/WORK=[^,]*/){
  val=substr($0,RSTART+5,RLENGTH-5)
  if(val!~/\([a-zA-Z]+\)/){ print val }
}
' Input_file

Explanation: Adding detailed explanation for above.

awk '                                    ##Starting awk program from here.
match($0,/WORK=[^,]*/){                  ##Using match function to match WORK= till comma comes.
  val=substr($0,RSTART+5,RLENGTH-5)      ##Creating val with sub string of match regex here.
  if(val!~/\([a-zA-Z]+\)/){ print val }  ##checking if val does not has ( alphabets ) then print val here.
}
' Input_file                             ##Mentioning Input_file name here.

This might work for you (GNU sed):

sed -n '/.*WORK=\([^,]\+\).*/{s//\1/;/(.*)/!p}' file

Extract the string following WORK= and if that string does not contain (...) print it.

This will work if there is only zero or one occurrence of WORK= and that the exclusion depends only on the (...) occurring within that string and not other following fields.

For a global solution with the same stipulations for parens:

sed -n '/WORK=\([^,]\+\)/{s//\n\1\n/;s/[^\n]*\n//;/(.*).*\n/!P;D}' file

N.B. This prints each such string on a separate line an excludes empty strings.

Related