Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select rows that are equal to different values in awk

Tags:

awk

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?

like image 983
Alejandro Avatar asked Oct 16 '25 02:10

Alejandro


2 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.

like image 110
RavinderSingh13 Avatar answered Oct 18 '25 06:10

RavinderSingh13


Perfect answer from RavinderSingh13!

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

awk '$1~/^[13]$/' Input_File
like image 24
F. Knorr Avatar answered Oct 18 '25 08:10

F. Knorr