wc -w
will output the word count and file name for each of its arguments. So the command wc -w myfile.txt
will give you something like:
42 myfile.txt
However, where wc
doesn't know the filename, it simply outputs the count. You can hide the file name from it by using input redirection as wc
is one of those commands that will read standard input if you don't explicitly name a file. This can be done with:
wc -w <myfile.txt
or:
cat myfile.txt | wc -w
although the latter is inefficient in this case and better where the input is more complex than just the contents of some file.
The reason that wc
doesn't know the file name in wc -w <myfile.txt
is because the shell opens the file and attaches it to the standard input of the wc
process. The shell also never passes the <myfile.txt
along to the wc
program's command line arguments. Many programs like wc
have code along the lines of:
FILE * infile;
if (argc == 0)
infile = stdin;
else
infile = fopen (argv[1]], "r");
to select either standard input or open a known file name. In the former case, no name is available to the program.