What is the behavior of the wc command?
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 command "wc", and in "myDirtVar" I get something like: "9 file.txt"? I quoted "integer" because I know that everything is treated as a string by default in Bash, but I can't figure out the difference in behavior between the first and second expressions. What is the specific effect of the "<" redirection in this case?
source to share
wc
will default to a filename, allowing it to be used across multiple files (and have a result for all of them). If no filename is specified, "standard input" is used, which is usually console input, and the filename is not printed. <
you must specify an "input redirect" that reads input from the given file instead of using user input.
Put all this information together and you get the reason for the behavior wc
in your example
Question time: what will be the result cat file | wc -l
?
source to share
The page man
for wc
says:
NAME
wc - print newline, word, and byte counts for each file
SYNTAX
wc [OPTION]... [FILE]... wc [OPTION]... --files0-from=F
DESCRIPTION
Prints newlines, words and bytes for each FILE and total line if more than one FILE is specified.
So when you pass a file as an argument, it also prints the file name because you can pass more than one file in wc
so that it can count lines, so you know which file has that count. Of course, when you use stdin
it instead it doesn't know the filename so it won't print it.
Example
$ wc -l FILE1 FILE2
2 FILE1
4 FILE2
6 total
source to share