mohamed
mohamed

Reputation: 3

extract columns from multiple text files with awk

I am trying to extract column1 based on the values of column2. I would like to print the values of column1 only if column2 is ≤30 and greater than 5.

I also need to print the total number of the values of column1 based on the output. How can I do this with awk from multiple text files?

The sample of text file is shown below.

col1   col2  

aa     25
bb     4
cc     6
dd     23
aa     30

The output would be

aa
cc
dd
aa

Total number of aa is 2
Total number of cc is 1
Total number of dd is 1

Upvotes: 0

Views: 532

Answers (1)

Fredrik Pihl
Fredrik Pihl

Reputation: 45634

Something like this to get you started:

{ if ($2 <= 30 && $2 > 5) {
    print $1
    tot[$1] += 1 }
}
END {

  for (i in tot) {
    print "Total number of", i, "is", tot[i]
  }
}

Output:

$ awk -f i.awk input
aa
cc
dd
aa
Total number of aa is 2
Total number of cc is 1
Total number of dd is 1

Upvotes: 3

Related Questions