Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

awk syntax 1

Status
Not open for further replies.

polar1

MIS
May 14, 2001
31
US
I am new to awk and am having, what I think maybe a syntax problem.
Trying to add a row of numbers my command line is this:

echo '4 3 6 7'|awk '{count=$1} {for(length();count1=count;(total=(count++))<=NF) print "total is " total }'

two things I cannot figure out, how to define '{count=$1}' to represent each field, and I am trying to stop the 'for' loop when <=NF is reached.
 
You can refer to fields indirectly using $var where var contains the field number, so this is what you need to set up as your for loop counter.

The C syntax for for loops (which is similar to what awk uses) has three components, approximately:

Code:
for ( [i]init[/i] ; [i]expr[/i] ; [i]incr[/i] ) { [i]code[/i] }

init is where you initialise your counters.
expr is the expression which must remain "true" for your loop to continue executing.
incr is where you increment your counters.

All of these are optional (but you can easily end up with endless loops leaving some out).

So for your problem this should work:

Code:
echo '4 3 6 7' | awk '{ for (i=1; i<=NF; i++) { total+=$i } ; print "total is " total }'

Note that this code will execute for each individual line of input read from stdin.

Annihilannic.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top