Multiple Field separator in awk script

2019-08-02 19:53发布

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;

}

标签: linux shell awk
2条回答
别忘想泡老子
2楼-- · 2019-08-02 20:15

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

查看更多
beautiful°
3楼-- · 2019-08-02 20:22

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 
}
查看更多
登录 后发表回答