Reputation: 21
Here is a subset of a file for gnuplot with time in secs from 1/1/2000 and daily rainfall in mm:
559008000 13.500000
559094400 2.4000001
559180800 0.60000002
559267200 13.800000
559353600 6.3000002
559440000 0.30000001
559526400 0.0000000
559612800 0.0000000
559699200 0.0000000
559785600 0.0000000
I want to find the number of days since it rained (it's 4). First step is to reverse the file:
tac rainfile.txt
Now I'm looking for the first non-zero entry in column 2.
tac rainfile.txt | awk '$2 == "0.0000000" {++count} END {print count}'
gives me the total number of lines with zero, but how do I stop counting when I first hit a non-zero value?
Upvotes: 2
Views: 74
Reputation: 97948
You can grep
the lines you want and get the last one via tail
:
grep '^ *[0-9]\+ [0-9.]*[1-9][0-9.]*' input | tail -1
this gives:
559440000 0.30000001
to get the line number:
echo $(( $(tac in | grep -n ' [1-9][0-9.]* *$' -m 1 | cut -f1 -d:) - 1))
which gives:
4
Upvotes: -1
Reputation: 157967
I would just use awk
, tac
is not needed here:
awk '$2>0{d=0;next}{d++}END{print d}' rain.txt
tac
needs to loop through the file anyway. Sure, it does not need to compare numbers, but unless rainfile.txt
is really huge you shouldn't feel a difference. Otherwise see below...
About your initial solution with tac
, just add a next
and an exit
statement:
tac rain.txt | awk '$2 == "0.0000000"{++count;next}{exit}END{print count}'
Note that awk
will process the END
block after exit
has been called.
Upvotes: 2
Reputation: 133458
Could you please try following and let me know if this helps.
awk '($2==0){count++;next} {count=0} END{print count}' Input_file
Output will be 4
for same. Explanation will be simple, check if any 2nd field is equal to zero, if yes then increase variable named count's value to 1 and use next to skip all further statements. If this condition doesn't satisfy in any line then it will not come in this block and it will nullify the value of count. Finally when all lines are read in END bock print the variable count which is 4.
Upvotes: 1