Domanda

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?

È stato utile?

Soluzione

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.

Altri suggerimenti

This works because when you use < the shell is sourcing the contents of "file.txt" to the standard input of wc.

Also, note that wc -l will give you the number of lines in file.txt. If you really want the number of words irrespective on which line they are, you should use wc -w instead.

When you used wc -w file.txt it gave you the number of words inside "file.txt" and the filename because wc accepts many files as possible inputs, so it outputs the filename after the word count for you to know that file has those many words. For example, suppose you have these two files with their respective contents:

twoword.txt: foo bar

threeword.txt: foo bar test

then wc -w twoword.txt threeword.txt would give you:

2 twoword.txt
3 threeword.txt
5 total

thus showing how many words are there in each file then summing up them for total.

In your example, file.txt is being sent to stdin. Read up on what stdin, stout and stderr are here: Confused about stdin, stdout, and stderr

The man page for wc defines the behavior with no file parameter.

wc is reading the contents of file.txt from stdin and printing the number of words. It doesn't print the file name because it doesn't know what the file name is when it reads from stdin.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top