Search for pattern with alphanumeric and print the lines

Viewed 136

I have data in format

A  ((!(A1+A2)))
B  (A1A2)
C  (A1+A2)
D  (!(A1+A2)B1)
E  (!A1+!A2)
F  (!(!A1!A2)+A3+A4)
G  ((A1!A2)B1)

I want output as

E  (!A1+!A2)
F  (!(!A1!A2)+A3+A4)
G  ((A1!A2)B1)

I want to get that line which has ! only with alphanumeric.

I used

awk -F' ' '$2 ~ /\!/' file

And this also

awk '$2'~/^[(!)_[:alnum:]]+[(!)+_[:alnum:]]+$/' file

But this is listing all the lines which has ! along with ! in alphanumeric also.

5 Answers

I want to get that line which has ! only with alphanumeric:

You can just use this regex for matching ! followed by an alphanumeric character:

/![[:alnum:]]/

awk command:

awk '$2 ~ /![[:alnum:]]/' file

E  (!A1+!A2)
F  (!(!A1!A2)+A3+A4)
G  ((A1!A2)B1)
$ grep '![[:alpha:]]' file
E  (!A1+!A2)
F  (!(!A1!A2)+A3+A4)
G  ((A1!A2)B1)

$ awk '/![[:alpha:]]/' file
E  (!A1+!A2)
F  (!(!A1!A2)+A3+A4)
G  ((A1!A2)B1)

$ sed -n '/![[:alpha:]]/p' file
E  (!A1+!A2)
F  (!(!A1!A2)+A3+A4)
G  ((A1!A2)B1)

If that's not all you need then edit your question to more clearly state your requirements and provide sample input/output that that doesn't work for.

I guess I want to get that line which has ! only with alphanumeric means: not !(

$ awk '/![^(]/' file

Output:

E  (!A1+!A2)
F  (!(!A1!A2)+A3+A4)
G  ((A1!A2)B1)

If your real data is not so tight, you may want to throw in some space checking, for example: /! *[^(]/

Also with awk:

awk '/![[:alpha:]]+/' file         
E  (!A1+!A2)
F  (!(!A1!A2)+A3+A4)
G  ((A1!A2)B1)

Or

awk '/![[:alpha:]][[:digit:]]/' file
E  (!A1+!A2)
F  (!(!A1!A2)+A3+A4)
G  ((A1!A2)B1)

You can require a starting (leading) word boundary (\<) after !:

awk '$2 ~ /!\</' file

Note that whitespace is the default field separator pattern, you do not need -F' '.

See the online awk demo:

s='A  ((!(A1+A2)))
B  (A1A2)
C  (A1+A2)
D  (!(A1+A2)B1)
E  (!A1+!A2)
F  (!(!A1!A2)+A3+A4)
G  ((A1!A2)B1)'
awk '$2 ~ /!\</' <<< "$s"

Output:

E  (!A1+!A2)
F  (!(!A1!A2)+A3+A4)
G  ((A1!A2)B1)
Related