Select rows that are equal to different values in awk

Viewed 108

I have a data frame whose first column has representative numbers of animal breeds like that:

1 12M08413 12M08388 12M08414 1 -9 A A G G G G
1 12M08416 12M08412 12M08415 1 -9 A A A G G G
1 12M08422 12M08397 12M08421 1 -9 A A A G G G
2 12M08423 12M08395 12M08396 2 -9 A A G G G G
2 12M08424 12M08392 12M08425 1 -9 A A A G G G
2 12M08426 12M08399 12M08411 1 -9 A A G G G G
3 12M08428 12M08400 12M08403 2 -9 A A G G G G
3 12M08434 12M08410 12M08417 1 -9 A A G G G G
4 12M08435 12M08389 12M08394 1 -9 A A A G G G
4 12M08437 12M08390 12M08427 1 -9 A A A G G G

I would like to get the rows that are equal to 1 or 3 in the first column. For example:

1 12M08413 12M08388 12M08414 1 -9 A A G G G G
1 12M08416 12M08412 12M08415 1 -9 A A A G G G
1 12M08422 12M08397 12M08421 1 -9 A A A G G G
3 12M08428 12M08400 12M08403 2 -9 A A G G G G
3 12M08434 12M08410 12M08417 1 -9 A A G G G G

I have done:

awk -F, '$1 == c("1","3")' my_file.txt

But c(...) isn't correct. How I can do this?

3 Answers

Based on your shown samples, could you please try following.

awk '$1==1 || $1==3' Input_file

Explanation with OP's attempt fix: This simply looks if 1st field is either 1 OR 3 then print that line. Also you need not to use -F, part since that is for setting field separator to comma and you don't have comma separated lines.

Perfect answer from RavinderSingh13!

I probably would have used a regular expression (see comment from @Daweo):

awk '$1~/^[13]$/' Input_File

If you are interested in possible close to R solution: so far I know AWK do not have Doppelganger of R's vectors created using c(...), but there exist associative arrays i.e. holding key-value pairs, which support in check. in is true if given key exists, so your task might be accomplished following way, let file.txt be:

1 12M08413 12M08388 12M08414 1 -9 A A G G G G
1 12M08416 12M08412 12M08415 1 -9 A A A G G G
1 12M08422 12M08397 12M08421 1 -9 A A A G G G
2 12M08423 12M08395 12M08396 2 -9 A A G G G G
2 12M08424 12M08392 12M08425 1 -9 A A A G G G
2 12M08426 12M08399 12M08411 1 -9 A A G G G G
3 12M08428 12M08400 12M08403 2 -9 A A G G G G
3 12M08434 12M08410 12M08417 1 -9 A A G G G G
4 12M08435 12M08389 12M08394 1 -9 A A A G G G
4 12M08437 12M08390 12M08427 1 -9 A A A G G G

then

BEGIN{a["1"]=a["3"]=""}($1 in a){print}

output

1 12M08413 12M08388 12M08414 1 -9 A A G G G G
1 12M08416 12M08412 12M08415 1 -9 A A A G G G
1 12M08422 12M08397 12M08421 1 -9 A A A G G G
3 12M08428 12M08400 12M08403 2 -9 A A G G G G
3 12M08434 12M08410 12M08417 1 -9 A A G G G G

Explanation: I create array with keys "1" and "3" both holding empty string named a, then for every line in which first column is present I print it.

Related