3

I want to display the number of lines, words and characters, in a file, in separate lines?
I don't know anymore than using wc filename for this.

2

You can use tr:

wc filename | tr ' ' '\n' 

, or if you just want the numbers:

wc filename | tr ' ' '\n' | head -3
7
  • Great !! Thanks. Can you help me to extract just lines 2-4. I can pipe the output in the chain of head and tail but is there any single command operation possible?
    – Gaurav
    Sep 8 '14 at 7:20
  • Or I should ask it as a separate question if you want another +10. :)
    – Gaurav
    Sep 8 '14 at 7:30
  • @Gaurav wc filename | tr ' ' '\n' | tail -3 no need for a seperate question, but you can accept this answer of course (hint, hint). This only works if the filename has contains no spaces or other "special" characters (but if it did line number 4 would not be so interesting anyway).
    – Anthon
    Sep 8 '14 at 7:54
  • 2
    @Anthon: You can use wc < filename to prevent filename from being printed to output.
    – cuonglm
    Sep 8 '14 at 8:51
  • @gnouc I always forget that, thanks for reminding. But for what the OP commented later (just print word & byte count + filename (lines 2-4)), that would not help.
    – Anthon
    Sep 8 '14 at 8:56
2

I like using xargs -n XX to have XX items per line.

See:

$ wc a
 3  5 21 a
$ wc < a
 3  5 21
$ wc < a | xargs -n 1
3
5
21
2
printf %d\\n $(wc <file)

That will insert a newline between each of printf's arguments, which, when split on a default $IFS are the spaces between wc's output.

For example:

printf %d\\n $(wc <<< $(seq -s" some splitter $IFS" 100))
100
298
1975
1
  • Cleanest solution thank you
    – MitchellK
    Jan 7 '21 at 17:42
1

With shells with support for process substitution (ksh, zsh, bash), you could do something like:

read line word byte < <(wc < file)
echo "file has $line lines, $word words and $byte bytes"

With AT&T ksh or zsh,

wc < file | read line word byte

should also work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.