How to print the number of characters in each line of a text file How to print the number of characters in each line of a text file unix unix

How to print the number of characters in each line of a text file


Use Awk.

awk '{ print length }' abc.txt


while IFS= read -r line; do echo ${#line}; done < abc.txt

It is POSIX, so it should work everywhere.

Edit: Added -r as suggested by William.

Edit: Beware of Unicode handling. Bash and zsh, with correctly set locale, will show number of codepoints, but dash will show bytes—so you have to check what your shell does. And then there many other possible definitions of length in Unicode anyway, so it depends on what you actually want.

Edit: Prefix with IFS= to avoid losing leading and trailing spaces.


Here is example using xargs:

$ xargs -d '\n' -I% sh -c 'echo % | wc -c' < file