awk beginner question about putting some commands in a program file like abc.awk
i need to write this for counting lines between NR= 0-500, 500-1000,1000-1500 etc. till the end, and which start with 1.
awk "{NR<=500 && "/^1/" && sum+=1}; END {print sum}" 1.txt
awk "{NR>500 && NR<=1000 && "/^1/" && sum+=1}; END {print sum}" 1.txt
awk "{NR>1000 && NR<=1500 && "/^1/" && sum+=1}; END {print sum}" 1.txt
.....
here is my qu开发者_如何学Pythonestion, how can i put these in to a file(*.awk) to run at the same time..
you can try put these commands in a file eg myscript.awk
NR<=500 && /^1/ { sum1 += 1 }
NR>500 && NR<=1000 && /^1/ { sum2 += 1}
NR>1000 && NR<=1500 && /^1/ { sum3+=1 }
END { print sum1,sum2.sum3 }
then run on command line
awk -f myscript.awk 1.txt
you do not need to call awk on the same file 3 times! Its an example of inefficient coding.
you can out a shebang #!/usr/bin/awk -f
in the first line of your script only if you want to run it like ./myscript.awk
, otherwise , you can leave it out
If you want the script to be pure awk, you need a shebang line with a -f. Make this line one of the file:
#!/usr/bin/awk -f
(or adjust according to the location of the awk you want to use)
One big drawback of that approach is that you must hard code the path of awk in the script. The typical solution to that problem (to use /usr/bin/env) does not work with awk or sed, because they require the -f in the shebang. If you just want to use a shell script wrapper around your awk, you can do something like:
#!/bin/sh file=${1-1.txt} awk "{NR<=500 && "/^1/" && sum+=1}; END {print sum}" $file awk "{NR>500 && NR<=1000 && "/^1/" && sum+=1}; END {print sum}" $file awk "{NR>1000 && NR<=1500 && "/^1/" && sum+=1}; END {print sum}" $file
Untested, but this should replace all those duplicated lines:
awk '/^1/ {sum++} NR % 500 == 0 {print sum; sum=0} END {print sum}' 1.txt
精彩评论