Awk is pretty powerful command line utility to filter lines from a stream. Here are some awk if condition
examples.
Data used in these examples:
1 string1 2 string2 100 string3
Awk if example – print full line based on a field value
Print entries (full line) where first column is greater than certain threshold. Here $0
represents full line.
cat data1.txt | awk '{if ($1 > 1) print $0}'
2 string2 100 string3
Env: GNU bash, version 4.2.46
Awk if example – print specific field based on a field value
Print entries (2nd field only) where first column is greater than certain threshold.
cat data1.txt | awk '{if ($1 > 1) print $2}'
string2 string3
Env: GNU bash, version 4.2.46
Awk if example – conditional sum
Find sum of first column values where column value is less that certain threshold. This can be used to exclude outliers.
cat data1.txt | awk '{if ($1 <= 10) S+=$1} END {print S}'
3
Env: GNU bash, version 4.2.46
Awk if example – multiple statements in if
Find avg of first column values where column value is less that certain threshold.
cat data1.txt | awk '{if ($1 <= 10) {S+=$1;C+=1}} END {print S/C}'
1.5
Env: GNU bash, version 4.2.46