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

I would like to print the number of characters in each line of a text file using the unix command. I know it's just with powershell

gc abc.txt | % {$_.length} 

but i need a unix command.

+55
unix shell awk sed
Jan 09 '12 at 10:00
source share
6 answers

Use awk.

 awk '{ print length($0); }' abc.txt 
+111
Jan 09 2018-12-12T00:
source share
 while read -r line; do echo ${#line}; done < abc.txt 

This is POSIX, so it should work everywhere.

Edit: Added -r, as suggested by William.

+12
09 '12 at 10:05
source share

Here is an example of using xargs :

 $ xargs -d '\n' -I% sh -c 'echo % | wc -c' < file 
+1
Feb 07 '15 at 16:31
source share

I tried the other answers listed above, but they are very far from decent solutions when working with large files - especially when one line size takes more than ~ 1/4 of the available RAM.

Both bash and awk slurp are the entire line, although this is not necessary for this problem. bash will fail if the line is too long, even if you have enough memory.

I implemented an extremely simple, rather non-optimized python script, which when testing with large files (~ 4 GB per line) does not smooth out and, of course, is a better solution than the ones provided.

If this is temporary critical production code, you can rewrite the ideas in C or improve the optimization when reading (instead of reading only one byte at a time), after testing that this is really a bottleneck.

The code assumes that newline is a newline character, which is a good guess for Unix, but YMMV on Mac OS / Windows. Ensure that the file ends with a line to ensure that the number of last line characters is not skipped.

 from sys import stdin, exit counter = 0 while True: byte = stdin.buffer.read(1) counter += 1 if not byte: exit() if byte == b'\x0a': print(counter-1) counter = 0 
+1
Feb 11 '15 at 21:08
source share

Try the following:

 while read line do echo -e |wc -m done <abc.txt 
0
Jan 09 '12 at 10:09
source share

Do not use AWK, use sed instead! Using sed, you can simulate a full decade add :

 sed -n 's/./a/g; s/^$/0/; :c /a/! be; s/^a/1/; s/0a/1/; s/1a/2/; s/2a/3/; s/3a/4/; s/4a/5/; s/5a/6/; s/6a/7/; s/7a/8/; s/8a/9/; s/9a/a0/; /a/ bc; :ep' abc.txt 

This command prints the number of characters in each line of the text file abc.txt .

-one
Feb 01 '19 at 14:08
source share



All Articles