Is it possible to use wc to count the chars of each line instead of the total amount of chars?


echo -e foo\\nbar\\nbazz | grep -i ba



So why doesn't echo -e foo\\nbar\\nbazz | grep ba | wc -m return a list of the lengths of those words? (3 and 4)


P.S.: why are linefeeds counted with wc -m ? wc -l counts the newlines, so why should wc -m count them too?

  • 1
    That's wc -c you are looking for. Oct 26, 2017 at 16:08
  • 4
    @αғsнιη, wc -c counts the bytes while wc -m counts the characters, but that won't make a difference in this instance where all characters in that sample are single-byte ones. Oct 26, 2017 at 16:34
  • in fact echo 'Stéphane' | wc -m =9 but echo 'Stéphane' | wc -c =10
    – JJoao
    Oct 26, 2017 at 16:37

3 Answers 3


wc counts over the whole file; You can use awk to process line by line (not counting the line delimiter):

echo -e "foo\nbar\nbazz\n" | grep ba | awk '{print length}'

or as awk is mostly a superset of grep:

echo -e "foo\nbar\nbazz\n" | awk '/ba/ {print length}'

(note that some awk implementations report the number of bytes (like wc -c) as opposed to the number of characters (like wc -m) and others will count bytes that don't form part of valid characters in addition to the characters (while wc -m would ignore them in most implementations))


Here's another way to do it.

for line in $(echo -e foo\\nbar\\nbazz); do echo ${#line}; done



You can iterate over the output lines and run wc for each:

echo -e foo\\nbar\\nbazz | \
grep -i ba | \
while read LINE; do echo $LINE | wc -m; done

If you don't want to count the newline characters, you can remove them:

echo -e foo\\nbar\\nbazz | \
grep -i ba | \
while read LINE; do echo ${LINE::-1} | wc -m; done

(The above assumes there is a newline after after line, so if the last line does not include a trailing newline, the count will be off.)


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .