Multiple Field separator in awk script

拥有回忆 提交于 2020-03-04 08:40:12

问题


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;

}

回答1:


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




回答2:


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 
}


来源:https://stackoverflow.com/questions/18805385/multiple-field-separator-in-awk-script

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!