Whats is the behaviour of the “wc” command?

爱⌒轻易说出口 提交于 2019-12-20 02:29:43

问题


For example:

myCleanVar=$( wc -l < myFile )
myDirtVar=$( wc -l myFile )

echo $myCleanVar
9

echo $myDirtVar
9 myFile

why in "myCleanVar" I get an "integer" value from the "wc" command and in "myDirtVar" I get something like as: "9 file.txt"? I quoted "integer" because in know that in Bash shell by default all is treated as a string, but can't understand the differences of the behaviour of first and second expression. What is the particular effect of the redirection "<" in this case?


回答1:


wc will list by default the name of file allowing you to use it on more than one file (and have result for all of them). If no filename is specified, the "standard input", which is usually the console input, is used, and no file name is printed. The < is needed to specify an "input redirection", that is read the input from given file instead of using user input.

Put all this information together and you get the reason of wc's behavior in your example

Question time: what would be the output of cat file | wc -l ?




回答2:


The man page for wc says:

NAME

   wc - print newline, word, and byte counts for each file

SYNOPSIS

   wc [OPTION]... [FILE]...
   wc [OPTION]... --files0-from=F

DESCRIPTION

Print newline, word, and byte counts for each FILE, and a total line if more than one FILE is specified.

So when you pass the file as an argument it will also print the name of the file because you could pass more than one file to wc for it to count lines, so you know which file has that line count. Of course when you use the stdin instead it does not know the name of the file so it doesn't print it.

Example

$ wc -l FILE1 FILE2
  2 FILE1
  4 FILE2
  6 total


来源:https://stackoverflow.com/questions/25348406/whats-is-the-behaviour-of-the-wc-command

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