ComputerFellow
ComputerFellow

Reputation: 12108

Awk - How to cut a line, check if a column matches something, print another column?

I have a laaaaaarge file like this:

VENDOR|QTY|ITEM|PRICE
2|3|Sugar|15
3|3|Coffee|35
4|244|Sugar2|55
33|2|Pizza|36
3|3|Pizza|55
5|5|Pizza2|33
6|6|Pizza3|44

How do I print VENDOR and PRICE IFF ITEM is Pizza?

I've tried grep but it's slow.

I could write a python code like so,

for line in file:
    fields = line.split('|')
    if fields[2] == 'Pizza':
        print fields[0], fields[-1]

but I want to do it in Awk from the shell itself. How do I do this?

Update

How do I check substrings as well?

I want to output VENDOR and PRICE if Pizza occurs in ITEM?

Output should be:

33|36
3|55
5|33
6|44

Upvotes: 3

Views: 12096

Answers (1)

fedorqui
fedorqui

Reputation: 290105

This makes it:

$ awk -F\| '$3=="Pizza" {print $1,$4}' file
33 36
3 55

Explanation

  • -F\| set | as field delimiter.
  • $3=="Pizza" check if the 3rd field is "Pizza".
  • {print $1,$4} prints the 1st and 4th fields.

Update

I want to output VENDOR and PRICE if Pizza occurs in ITEM?

$ awk 'BEGIN{OFS=FS="|"} $3~/Pizza/ {print $1,$4}' file
33|36
3|55
5|33
6|44

Explanation

  • $3~/Pizza/ checks "occurs", as well as $3=="Pizza checks exact matching.
  • BEGIN{OFS=FS="|"} sets the (input & output) field separator to be |.

Upvotes: 11

Related Questions