Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

awk for multiple patterns

My file looks like:

L   0   256 *   *   *   *   *
H   0   307 100.0   +   0   0
S   30  351 *   *   *   *   *
D   8   27  *   *   *   *   99.3    
C   11  1   *   *   *   *   *   

for my script I would like to start by awk print $0 for certain lines using $1

Such as

awk '{if ($1!="C") {print $0}  else if ($1!="D") {print $0}}'

But, there has to be a way to combine "C" and "D" into one IF statement... right?

For example if I want to search for == L,H,S ie... NOT C or D how would I right this?

like image 510
jon_shep Avatar asked Oct 29 '12 20:10

jon_shep


People also ask

What is pattern matching in awk?

Any awk expression is valid as an awk pattern. The pattern matches if the expression's value is nonzero (if a number) or non-null (if a string). The expression is reevaluated each time the rule is tested against a new input record.

What does next mean in awk?

The next statement forces awk to immediately stop processing the current record and go on to the next record. This means that no further rules are executed for the current record, and the rest of the current rule's action isn't executed.

What is awk in shell script?

Awk is mostly used for pattern scanning and processing. It searches one or more files to see if they contain lines that matches with the specified patterns and then perform the associated actions. Awk is abbreviated from the names of the developers – Aho, Weinberger, and Kernighan.


3 Answers

Your present condition is not correct as both $1!="C" and $1!="D" can't be false at the same time. Hence, it will always print the whole file.

This will do as you described:

awk '{if ($1!="C" && $1!="D") {print $0}}'  file
like image 85
P.P Avatar answered Nov 24 '22 08:11

P.P


Using awk, you can provide rules for specific patterns with the syntax

awk 'pattern {action}' file

see the awk manual page for the definition of a pattern. In your case, you could use a regular expression as a pattern with the syntax

awk'/regular expression/ {action}' file

and a basic regular expression which would suit your needs could be

awk '/^[^CD]/ {print $0}' file

which you can actually shorten into

awk '/^[^CD]/' file

since {print $0} is the default action, as suggested in the comments.

like image 21
Vincent Nivoliers Avatar answered Nov 24 '22 09:11

Vincent Nivoliers


awk '$1 ~ /[CD]/' file

awk '$1 ~ /[LHS]/' file

awk '$1 ~ /[^LHS]/' file

awk '$1 !~ /[LHS]/' file
like image 26
Ed Morton Avatar answered Nov 24 '22 08:11

Ed Morton