0

How can I select all rows in a text file based on different values of a particular column? The desired values are not in a specific interval.

A short example of what I expect is given below.

My data stored in a text file input.txt

1.0     21
2.5     23
4.0     21
6.5     45
9.0     30
16.5    46
2.0     78
1.0     20
1.6     19
2.5     25
4.0     40
5.2     16
6.5     25
9.0     47
10.0    14
16.5    60
18.5    65
20.0    57
.
.etc

I want to select rows based on 1st column having values 2.5,6.5,16.5,..., etc

So the output will look like this. I don't want to sort output numerically by 1st column.

2.5     23
6.5     45
16.5    46
2.5     25
6.5     25
16.5    60

I am looking for solutions in awk or sed or paste

Thanks in advance.

0

1 Answer 1

2

You could simply string the numbers together as an awk condition:

$ awk '$1==2.5 || $1==6.5 || $1==16.5' file
2.5     23
6.5     45
16.5    46
2.5     25
6.5     25
16.5    60

That can get really annoying if you have a long list, of course. Another option is to save the numbers you want in another file:

$ cat wantedNums
16.5
2.5 
6.5 

And then use that to filter your input file:

$ awk 'NR==FNR{a[$1]++; next} $1 in a' wantedNums file
2.5     23
6.5     45
16.5    46
2.5     25
6.5     25
16.5    60
10
  • my problem is I have a lot of such desired values. Commented Sep 11, 2020 at 14:01
  • 1
    @terdon I have recently been told by Ed Morton that a[$1] is sufficient to populate an array "with indices only".
    – AdminBee
    Commented Sep 11, 2020 at 14:01
  • @terdon ... which would actually make this question a duplicate ...
    – AdminBee
    Commented Sep 11, 2020 at 14:04
  • 1
    @AdminBee well I'll be... That's excellent, I had never realized it! Thanks! And yes, there are several dupes of this, I just never find them easily. Yours will do nicely.
    – terdon
    Commented Sep 11, 2020 at 14:07
  • 1
    @linux_lover if you have many desired values, use the second approach in my answer as explained in the answer.
    – terdon
    Commented Sep 11, 2020 at 14:07

Not the answer you're looking for? Browse other questions tagged .