Amit Singh
Amit Singh

Reputation: 63

How to use Awk to filter rows using a column value under double quotes

"A","B",123,"C","AAB"
"A","BB",234,"CC","BA"
"AA","B",123,"CC","CBB"
"AA","BB",213,"C","CCA"

I want to get those rows where $1 == AA

 awk 'BEGIN { FS = ","; OFS = FS;} {if ($1=="AA") print}'

but its not working. It works if the data is not in double quotes.

Upvotes: 2

Views: 2641

Answers (2)

Inian
Inian

Reputation: 85825

Just match the literal " with an escape character. This is the straight-forward filter to match the literal "AA" on the first column. Since awk works on a pattern { action } basis, the condition match to see if first column is "AA" can be done directly without needing to use explicit { print }

If the condition is met for that line, awk is left with a condition as awk 1 file on which case the line is printed.

awk -v FS=, '$1=="\"AA\""' file

Also, you can avoid escapes, by putting the match string in a variable under single-quotes and let it match the variable

awk -v FS=, -v m='"AA"' '$1==m' file

Upvotes: 1

RavinderSingh13
RavinderSingh13

Reputation: 133700

Following awk may help you on same.

awk -F, '{val=$1;gsub(/\"/,"",val)} val=="AA"'  Input_file

Solution 2nd:

awk -F"[\",]" '$2=="AA"'  Input_file

Upvotes: 1

Related Questions