Reputation: 1755
I just really can not seem to understand AWK and how it works. I have this code
awk '{ for(i=0; i<NR; i++)print i}'
My file I am reading has four rows with with five columns. It ends up printing
0
1
2
3
0
1
2
3
0
1
2
3
0
1
2
3
0
1
2
3
Why is i resetting and getting printed out different so many times?
I just want to print one time for each line. I just can not seem to understand the for loops In AWK and printing out one line. Also could someone explain to me how AWK works?!?
I want to be able to go through each line and test an if statement if so print but my if statement will run just as many times as the lines in the program. I have tired looking everywhere for answers but there is just not enough stuff on AWK to find anything useful. I am looking for a pretty straight forward answer on how for loops, if statements, and how printing works in AWK. Thank you so much!!
Update question:
I want to read a file that has this content
0 0 0 1
0 0 0 0
0 1 0 1
2 0 0 0
I want to be able to go through each line and add all the numbers in the row and if the row's total is greater than 0 than print the line if not then do not print it.
also I want to be to just know how to go print a number for how many lines there are.
so if the file has 6 lines the output would be:
1
2
3
4
5
6
Thank you again!
Upvotes: 0
Views: 206
Reputation: 203189
awk reads one record at a time from your input file, splits the record into fields, and then executes your script on the current record where your script consists of
<condition> { <action> }
statements. action
is executed if condition
is true given the current record. The default condition is true and default action to print the current record.
To print every line from an input file with awk is:
awk '1' file
since 1
is a true condition and therefore invokes the default action of printing the current record.
For more info, get the book "Effective Awk Programming, Third Edition" by Arnold Robbins and update your question to provide sample input, desired out, and a more specific description of what you're trying to do if you're still unsure.
wrt your updated question, here's how to do the first part (I want to be able to go through each line and add all the numbers in the row and if the row's total is greater than 0 than print the line if not then do not print it.
)
$ cat file
0 0 0 1
0 0 0 0
0 1 0 1
2 0 0 0
$ awk '{sum=0; for (i=1;i<=NF;i++) sum+=$i} sum>0' file
0 0 0 1
0 1 0 1
2 0 0 0
I don't know why the second part of your question (I want to be to just know how to go print a number for how many lines there are
) is showing the expected output you posted. Please refer to the sample input file you posted and tell us what output you want from that input file. Oh wait, are you saying you want to print the line numbers from the file?
That'd just be:
$ awk '{print NR}' file
1
2
3
4
Upvotes: 2