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 strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

determining total number of fields in file 4

Status
Not open for further replies.

noiz

IS-IT--Management
Apr 19, 2001
17
US
Hello,

I'm trying to write a quick awk script that will display the total number of fields in a file. So that

Test file test file
test file test file
test file test file

will be listed as having 12 fields. etc.

Thanks in advance

zion
<><
=-)
 
Hi, noiz and rbobbitt!

Awk command that will display the total number of fields in a file, can be like this:

awk '{ sum += NF } END { print sum }' inputfile

Because awk's variables (other than built-ins) are initialized to the null string, by default. This null string has also numerical value zero. So, you can skip BEGIN section. I like this feature of awk and other scripting languages.

KP.
 
Of course it depends on what you mean by a field? In you first example the unix command wc -w testfile will do the same thing, and if you want to return just the 12, then you can do wc -w testfile | tr -s &quot; &quot; | cut -d&quot; &quot; -f2 ... (which I guess is just as complicated as using awk!

Greg.
 
Okay. Same idea.
Here is something really ugly. Could someone
show me how to write it entirely in awk?

#!/bin/sh
gen=`ls -l | awk ' { if ($! !~ /^d/) print $9}' > filelist`
$gen || echo $? ; exit 1 > /dev/null
for i in `cat filelist`
do
awk' {tot += NF} END { print tot, FILENAME }' $i
done

This gives you the files in the working directory and a field count the hard way;
and it is totally inelegant.
I am new here so if you have the time I would appreciate it.
 
Hi marsd-

This about as elegant as it gets and awk is not
needed at all in this situation!

for file in *
do
if test -f $file
then
wc -w $file
fi
done


Hope this helps!


flogrr
flogr@yahoo.com

 
One more question. How would i modify this to print number of characters and not number of fields

zion
<><
=-)
 
Hi noiz-

Just change the -w in the wc command to -c and
it will count characters and -l will count lines.

HTH


flogrr
flogr@yahoo.com

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top