Reputation: 11
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
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
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
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