0

I was reading this question, in which someone is trying to get the number of lines in a file from the shell. From the comments, I saw and implemented that the following:

$ wc -l myfile.txt
30213 myfile.txt

$ wc -l < <filename>
30213

What I don't understand is, what the < operator is doing here. Can someone explain why the < operator chops off the file name from the output in this case?

user3685285
  • 6,066
  • 13
  • 54
  • 95

2 Answers2

2

In the first case, the filename is supplied as an argument when calling wc, this causes wc to include it in the output.

In the second case, stdin is redirected from filename, this makes wc "unaware" of the file and thus not able to print its name. This is equivalent to calling cat filename | wc -l.

So to answer your question, operator < redirects input file descriptor to read from a given file. If descriptor number is not explicitly specified, then it defaults to standard input (fd 0). See here for a formal reference and here for a convenient description.

tomix86
  • 1,336
  • 2
  • 18
  • 29
2

wc outputs the file name as part of the output when it reads from a file.

The < redirects input and output between files/programs, following the direction of the "arrow". For more information on I/O redirection, this is a pretty handy link. The reason that the file name is "chopped off" is because wc is technically no longer reading from a file.

Odd822
  • 53
  • 7
  • 1
    `wc` is reading from a file, it just doesn't know the name of the file it is reading from. – William Pursell Jan 02 '18 at 20:24
  • 1
    @WilliamPursell I was under the impression that redirecting the input and output means that wc is just reading from its own stdin (now modified to the file) rather than accessing the file directly, is that not correct? – Odd822 Jan 02 '18 at 20:35
  • wc is reading from its stdin. Which is a file that it access directly. – William Pursell Jan 02 '18 at 21:33
  • 1
    @WilliamPursell What are you talking about? – 123 Jan 04 '18 at 11:53
  • I am talking about the fact that if you invoke `wc < file`, then the stdin of the process is the file. And `wc` accesses that file directly. What is confusing about that statement? Write a program that invokes `fseek` on stdin. Use `<` to connect a file to the stdin on an invocation of that program. fseek will (probably) succeed. Why? Because stdin is the file, and the program is accessing it directly. – William Pursell Jan 04 '18 at 15:28
  • @123 ^^ See previous comment. – William Pursell Jan 04 '18 at 15:29