2

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.

4
  • characters (like in wc -m) or bytes (like in wc -c or the 3rd field in wc's output)? Oct 27, 2017 at 12:42
  • Count lines with grep -c $ filename
    – Philippos
    Oct 27, 2017 at 12:55
  • 1
    Words could be counted with sed 's/[[:space:]]/\n/g' filename | grep -c .
    – Philippos
    Oct 27, 2017 at 13:03
  • I want to count characters (like in wc -m) Oct 27, 2017 at 21:51

1 Answer 1

3

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.

You must log in to answer this question.

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