multiple condition store in variable and use as if condition in awk

Viewed 62

table1.csv:

33622|AAA
33623|AAA
33624|BBB
33625|CCC
33626|DDD
33627|AAA
33628|BBB
33629|EEE
33630|FFF

Aims:

33622|AAA
33623|AAA
33624|BBB
33625|CCC
33626|DDD
33627|AAA
33628|BBB

Using command:

 awk 'BEGIN{FS="|";OFS="|"} {if($2=="AAA" && $2=="BBB" && $2=="CCC" && $2=="DDD"){print $1,$2}}' table1.csv

However, trying to be more automatic, since the categories may increase.

list1.csv:
AAA BBB CCC DDD

list=`cat list1.csv`
awk -v list=$list 'BEGIN{FS="|";OFS="|"} {if($2==list){print $1,$2}}' table1.csv

Which means, can I stored $2=="AAA" && $2=="BBB" ....... into a variable by using list1.csv?

Expected output:

33622|AAA
33623|AAA
33624|BBB
33625|CCC
33626|DDD
33627|AAA
33628|BBB

So, any suggestion on storing the multiple condition in one variable?

Thanks all!

2 Answers
$ awk 'NR==FNR{for(i=1;i<=NF;i++)a[$i];next}FNR==1{FS="|";$0=$0}($2 in a)' list table

Output:

33622|AAA
33623|AAA
33624|BBB
33625|CCC
33626|DDD
33627|AAA
33628|BBB

Explained:

$ awk '
NR==FNR {                # process list
    for(i=1;i<=NF;i++)   # hash all items in file
        a[$i]
    next                 # possibility for multiple lines
}
FNR==1 {                 # changing FS in the beginning of table file
    FS="|"
    $0=$0
}
($2 in a)' list table

Almost same logic Like James Brown's nice answer, just adding here a small variant which is setting field separator in Input_file places itself.

awk 'FNR==NR{for(i=1;i<=NF;i++){arr[$i]};next} ($2 in arr)' list FS="|" table

Explanation: Adding detailed explanation for above.

awk '                   ##Starting awk program from here.
FNR==NR{                ##Checking condition which will be TRUE when list is being read.
  for(i=1;i<=NF;i++){   ##Going through all fields here.
    arr[$i]             ##Creating arr with index of current column value here.
  }
  next                  ##next will skip all further statements from here.
}
($2 in arr)             ##Checking condition if 2nd field is present in arr then print that line from table file.
' list FS="|" table     ##mentioning Input_file(s) here and setting FS as | before table file.
Related