i have following code that gives me output as number of lines and words in a file. how can i use one more FS(file separator) that can be used to count total characters.??
(the output should be same as wc file command
)
BEGIN {
FS="\n| ";
}
{
for(i=1;i<=NF;i++)
w++
l++
}
END {
print "Total no of Lines:"l;
print "Total no of words:"w;
}
You can use the built in variable "$0" and function "length"
BEGIN {
FS="\n| ";
}
{
for(i=1;i<=NF;i++)
w++
l++
c += length($0)+1
}
END {
print "Total no of Lines:"l;
print "Total no of words:"w;
print "Total no of chars:"c;
}
Edit: Add +1 to length to account for newline
Note, that with that field separator the script will count too many "words" since fields are considered words here and every space becomes a field separator.
Also, awk
can only give a correct result for proper text files, where limits like maximum line lengths are observed and the last lines ends with a newline ..
The script could be simplified further a bit
{
w+=NF
c+=length+1
}
END {
print "Total no of lines:" NR
print "Total no of words:" w
print "Total no of chars:" c
}