user2812658
user2812658

Reputation: 11

How to selectively grep?

I have a file that's structured as follows:

particle 1
0.1   0.988
0.2   0.975
0.2   0.945
0.3   0.900
...
...
particle 2
0.1   0.988
0.2   0.965
0.2   0.945
0.2   0.935
0.3   0.900
...

How do I grep only the first occurrence of 0.2 under each particle? e.g I want to grep something like

particle 1
0.2 0.975
particle 2
0.2 0.965

Thanks in advance!!

Upvotes: 1

Views: 124

Answers (4)

Ed Morton
Ed Morton

Reputation: 203209

Assuming you only want to print the particle id when there is a 0.2 under it and that the particle ids in your sample input are placeholders but do start with non-digits in your real file:

$ cat file
particle 1
0.1   0.988
0.2   0.975
0.2   0.945
0.3   0.900
...
particle 2
0.1   0.988
0.3   0.900
0.4   0.900
...
particle 3
0.1   0.988
0.2   0.965
0.2   0.945
0.2   0.935
0.3   0.900
...

$ awk '/^[^[:digit:]]/{p=$0} p && ($1==0.2){ print p ORS $0; p="" }' file
particle 1
0.2   0.975
particle 3
0.2   0.965

Upvotes: 0

potong
potong

Reputation: 58371

This might work for you (GNU sed):

sed -r '/particle/b;/^0\.2/!d;:a;$!N;/^(0\.2\s).*\n\1/s/\n.*//;ta;P;D' file

If the line contains particle print it. If the line doesn't start 0.2 delete it. Delete the second line if it begins 0.2 otherwise print the first line.

Upvotes: 0

michael501
michael501

Reputation: 1482

how about grep

grep -E '^partice|^.2' f

Upvotes: 0

Kent
Kent

Reputation: 195029

this awk one-liner could help:

awk '/particle/{print;p=1}p&&/^0\.2/{print;p=0}' file

add a test:

kent$  cat f
particle 1
0.1 0.988
0.2 0.975
0.2 0.945
0.3 0.900
.....
.....
particle 2
0.1 0.988
0.2 0.965
0.2 0.945
0.2 0.935
0.3 0.900

kent$  awk '/particle/{print;p=1}p&&/^0\.2/{print;p=0}' f
particle 1
0.2 0.975
particle 2
0.2 0.965

Upvotes: 6

Related Questions