Score:1

zsh: Understanding command output from wc and passing it to other commands

gq flag

I'm trying to create a complex command (using shell substitutions and arithmetic expressions) and I was wondering if anyone could helpme understand the output of the wc command.

For instance, here are a couple of examples:

[11:10:33] labreu:~ $ wc -l test.txt
5 test.txt
[11:10:40] labreu:~ $ cat test.txt| wc -l
5

Why does the command return different values? I've tried looking at its man page, but there's nothing there about it...

Btw, I'm only asking about this because I was trying to skip x lines of a file with the following command:

[11:25:35] labreu:~ $ tail -n "+$(( $(wc -l test.txt)-2 ))" test.txt                       
zsh: bad math expression: operator expected at `test.txt-2...'

After noticing that wc returns number_of_lines filename and that using pipes (or redirection produces a different result), I managed to get what I needed by using something like this:

tail -n "+$(( $(wc -l<test.txt )-2 ))" test.txt

tail -n "+$(( $(cat test.txt | wc -l )-2 ))" test.txt 

Anyway, the main question remains: why does the wc command returns different output when used within a pipe (or with input redirection)?

Thanks

Score:0
cn flag

The 1st method you use on command line. The 2nd method can be used when coding.

The command itself can do this for more than 1 file so it needs to tell you what amount of lines belongs to what file.

$ wc -l *.xml
   712 1.xml
  3055 2.xml
   464 3.xml
  3055 4.xml

wc -l itself does not distinguish between 1 file, a wildcard, or multiple files. To do it without the name I tend to use wc -l < file.txt so with a redirect.

The concatenate method/piped version is always 1 file so the name of the file is implied. A for loop would still imply 1 file per wc -l but repeating the same multiple times.

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.