I have made programs using wc
commands, but I want to know how to count the number of lines, words, and characters without using wc
in a file using a shell script.
1 Answer
To count the number of bytes (like wc -c
)
< file LC_ALL=C tr -c '\n' '[\n*]' | grep -c '^'
To count the number of newline characters (like wc -l
):
< file LC_ALL=C tr -cd '\n' | grep -c '^'
For words (like wc -w
), assuming a POSIX compliant tr
like FreeBSD's (not GNU's) and assuming the file doesn't contain illegal byte sequences:
< file tr -cs '[:space:]' '[x*]' | tr -cs x '[\n*]' | grep -c x
For characters (like wc -m
), same restrictions:
< file tr -c '\n' '[\n*]' | grep -c '^'
On the output of:
printf '\0foo\u2006and \r\fbar\nbaz'
They give respectively 20, 1, 4, 18, like wc
on a FreeBSD system in a en_GB.UTF-8 locale.
wc -m
) or bytes (like inwc -c
or the 3rd field inwc
's output)?grep -c $
filenamesed 's/[[:space:]]/\n/g' filename | grep -c .