Friday, October 7, 2022

[SOLVED] How does "wc -w < file.txt" work?

Issue

I was trying to get only the number of words in a file using wc. wc -w file.txt gives me that plus the file name. I don't want the file name. So, I saw that wc -w < file.txt works.

I don't understand how this command works. I cannot even add a comment below the answer where I saw this command.

Why does it not print filename in the case of wc -w < file.txt?


Solution

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.



Answered By - paxdiablo
Answer Checked By - David Marino (WPSolving Volunteer)