This challenge is similar to this old one, but with some unclear parts of the spec hammered out and less strict I/O requirements.

Given an input of a string consisting of only printable ASCII and newlines, output its various metrics (byte, word, line count).

The metrics that you must output are as follows:

  • Byte count. Since the input string stays within ASCII, this is also the character count.

  • Word count. This is wc's definition of a "word:" any sequence of non-whitespace. For example, abc,def"ghi" is one "word."

  • Line count. This is self-explanatory. The input will always contain a trailing newline, which means line count is synonymous with "newline count." There will never be more than a single trailing newline.

The output must exactly replicate the default wc output (except for the file name):

llama@llama:~$ cat /dev/urandom | tr -cd 'A-Za-z \n' | head -90 > example.txt
llama@llama:~$ wc example.txt
  90  165 5501 example.txt

Note that the line count comes first, then word count, and finally byte count. Furthermore, each count must be left-padded with spaces such that they are all the same width. In the above example, 5501 is the "longest" number with 4 digits, so 165 is padded with one space and 90 with two. Finally, the numbers must all be joined into a single string with a space between each number.

Since this is , the shortest code in bytes will win.

(Oh, and by the way... you can't use the wc command in your answer. In case that wasn't obvious already.)

Test cases (\n represents a newline; you may optionally require an extra trailing newline as well):

"a b c d\n" -> "1 4 8"
"a b c d e f\n" -> " 1  6 12"
"  a b c d e f  \n" -> " 1  6 16"
"a\nb\nc\nd\n" -> "4 4 8"
"a\n\n\nb\nc\nd\n" -> " 6  4 10"
"abc123{}[]()...\n" -> " 1  1 16
"\n" -> "1 0 1"
"   \n" -> "1 0 4"
"\n\n\n\n\n" -> "5 0 5"
"\n\n\na\nb\n" -> "5 2 7"
  • 2
    \$\begingroup\$ I'm gonna VTC the old one as a dupe of this one because this one is a much better challenge. \$\endgroup\$
    – user45941
    Commented Feb 26, 2016 at 3:26
  • \$\begingroup\$ Should the empty input be supported ? \$\endgroup\$
    – Ton Hospel
    Commented Feb 26, 2016 at 16:32
  • \$\begingroup\$ I don't think so, he said all inputs end with \n. \$\endgroup\$ Commented Feb 26, 2016 at 17:04

23 Answers 23


Perl, 49 bytes

Added +3 for -an0

Input on STDIN or 1 or more filenames as arguments. Run as perl -an0 wc.pl


/\z/g;pos=~//;printf"%@+d %@+d $`


-n0      slurps the whole input into $_ and says we will do our own printing
-a       tells perl to split the input on whitespace into array @F
/\z/g    Matches the absolute end of the input. g modifier so the position 
         is remembered in pos which will now contain the input length
pos=~//  An empy regex repeats the last succesful match, so /\z/ again.
         After that $` will contain the the number of input characters and
         the array @+ will contain the length of this number
printf   All preparation is complete, we can go print the result
"%@+d"   will become e.g. %6d if the number of characters is a number of
         length 6, so lines and words will get printed right aligned 
         in a field of length 6.
$`       $` we can directly interpolate since it won't contain a %
y/\n//   Count the number of newlines in $_
~~@F     The array of words @F in scalar context gives the number of words

Pyth, 21 bytes


Test suite

Pyth has some very nice built-ins here. We start by making a list ([) of the newlines in the string (@bQ), the words in the string (cQ)) and the string itself (Q). Then, we pad (.[) the length of each string (ld) with spaces (; in this context) out to the length of the number of characters (l`lQ). Finally, join on spaces (jd).


Python 2, 100 77 bytes

This solution is a Python function that accepts a multi-line string and prints the required counts to stdout. Note that I use a format string to build a format string (which requires a %% to escape the first format placeholder).

Edit: Saved 23 bytes due to print optimisations by Dennis.

def d(b):c=len(b);a='%%%us'%len(`c`);print a%b.count('\n'),a%len(b.split()),c

Before the minifier, it looks like this:

def wc(text) :
    size = len(text);
    numfmt = '%%%us' % len(`size`);
    print numfmt % text.count('\n'), numfmt % len(text.split()), size

POSIX awk, 79 75 67 65 bytes

{w+=NF;c+=length+1}END{d=length(c)"d %";printf"%"d d"d\n",NR,w,c}

Edit: saved 4 bytes since POSIX allows a bare length, saved 7 bytes by discounting the invocation part, and saved two bytes thanks to Doorknob's tip for adding d % to d.

This was originally for GNU awk, but best I can tell, it uses only POSIX awk functionality.

Better formatted:

gawk '{
  w += NF
  c += length($0) + 1  # length($0) misses the newline
  d = length(c) # GNU awk's length returns the length of string representation of number
  printf "%"d"d %"d"d %d\n", NR, w, c
  • \$\begingroup\$ @Doorknob OK, thanks for that. Guess you saw the chat conversation? Also, that question should graduate from faq-proposed to faq. \$\endgroup\$
    – muru
    Commented Feb 26, 2016 at 12:26
  • 1
    \$\begingroup\$ Oh, I didn't see you in chat; your answer just popped up in my inbox :P I was the one who added [faq-proposed] to that question, so maybe I'll check in the mod room before upgrading it to [​faq]. \$\endgroup\$
    – Doorknob
    Commented Feb 26, 2016 at 12:28
  • 1
    \$\begingroup\$ Setting d to length(c)"d %" should allow you to change the printf to "%"d d"d\n", which saves two bytes. \$\endgroup\$
    – Doorknob
    Commented Feb 26, 2016 at 12:32
  • 1
    \$\begingroup\$ @Doorknob indeed, thanks! Guess it's not the exotic, but the mundane that saves bytes. \$\endgroup\$
    – muru
    Commented Feb 26, 2016 at 12:35

Seriously, 39 bytes

╜ck`#╛#"{:>%d}"%f`M' j

Try it online!

Explanation (newlines are replaced with \n):

"\n "╩╜l;$l╝@╜sl'\n╜ck`#╛#"{:>%d}"%f`M' j
"\n "                                      push a string containing a newline and a space
     ╩                                     push input to register 0 (we'll call it s)
      ╜l;                                  push two copies of len(s) (byte count)
         $l╝                               push len(str(len(s))) to register 1
                                            (this will serve as the field width in the output)
            @╜sl                           push word count by getting the length of the list formed by
                                            splitting s on spaces and newlines
                '\n╜c                      count newlines in input
                     k                     push stack to list
                      `#╛#"{:>%d}"%f`M     map:
                       #                     listify
                        ╛#                   push reg 1 (field width), listify
                          "{:>%d}"           push that string
                                  %          do old-style string formatting for field width
                                   f         do new-style string formatting to pad the field appropriately
                                      ' j  join on spaces
  • \$\begingroup\$ I cannot fidn any documentation for this language, can you provide a link? \$\endgroup\$
    – JohnEye
    Commented Feb 26, 2016 at 12:58
  • 2
    \$\begingroup\$ @JohnEye, github.com/Mego/Seriously \$\endgroup\$
    – awesoon
    Commented Feb 26, 2016 at 12:59

AppleScript, 253 bytes

This assumes that AppleScript's text item delimiters are set to space (if I need to count the stuff to force that assumption, I'll add it).

set w to(display dialog""default answer"")'s text returned
set x to b(w)
set y to w's text item's number
set z to w's paragraph's number
a(x,z)&z&a(x,y)&y&" "&x
on a(x,n)
set o to" "
repeat b(x)-b(n)
set o to o&" "
on b(n)
count(n as text)

CJam, 31 26 bytes


Try it online!

How it works

q_                         e# Read all input from STDIN and push two copies.
  )                        e# Pop the last character (linefeed) of the second copy.
   /                       e# Split the remaining string at linefeeds.
    _                      e# Push a copy.
     S*                    e# Join the copy, separating by spaces.
       S%                  e# Split at runs of spaces.
         @_                e# Rotate the original input on top and push a copy.
           ]               e# Wrap all four items in an array.
            :,             e# Get the length of each item.
              :s           e# Cast the lengths (integers) to strings.
                )          e# Pop the last length (byte count).
                 ,         e# Get the number of digits.
                  f{Se[}   e# Left-pad all three length with spaces to that length.
                        S* e# Join, separating by spaces.

Julia, 112 81 bytes

f(s,n=endof,l="$(n(s))",g=r->lpad(n(split(s,r))-1,n(l)))=g(r"\n")" "g(r"\S+")" "l

This is a function that accepts a string and returns a string.

We save the following as function arguments:

  • n = endof function, which gets the last index of an indexable collection (in this case is the length of the string)
  • l = "$(n(s)), the length of the input converted to a string using interpolation
  • A lambda function g that accepts a regular expression and returns the length - 1 of the input split on that regex, left padded with spaces to match the length of l.

We get the number of lines using g(r"\n") and the number of words using g(r"\S+"), then we join those together with l delimited by spaces.

Saved 31 bytes thanks to Dennis!


MATL, 38 bytes


You can try it online! This shouldn't be so long though...

Explanation, for the calculation,

'\n'32cZt  %// Takes implicit input and replaces any \n with a space
tt         %// Duplicate that string twice
nGnw-w     %// Length of the string with \n's minus length with spaces to give number of \n's
PZvPYbnq   %// Take string with spaces, flip it, remove leading spaces, flip it again,
           %// split on spaces, find length and decrement for number of words
bn         %// get length of string with spaces, the number of characters

The last part does the output formatting

vvV!       %// concatenate the 3 numbers to a column vector, convert to string and transpose
3Z"v       %// make string '   ' and concatenate on the bottom of previous string
X:!        %// linearise and transpose to get correct output (impicitly printed)
  • \$\begingroup\$ Nicely done! Maybe remove the "debug" flag in the Try it online link? \$\endgroup\$
    – Luis Mendo
    Commented Feb 26, 2016 at 10:45
  • \$\begingroup\$ Ahh whoops! Thanks for the heads up! \$\endgroup\$
    – David
    Commented Feb 26, 2016 at 11:16
  • \$\begingroup\$ I think you can replace !3Z"vX:! by Z{Zc (cellstr followed by strjoin) \$\endgroup\$
    – Luis Mendo
    Commented Feb 26, 2016 at 11:20

Jelly, 14 bytes


Try it online!

-1 thanks to Dennis.


JavaScript (ES6), 115 bytes

s=>[/\n\/g,/\S+/g,/[^]/g].map(r=>l=(s.match(r)||[]).length).map(n=>(' '.repeat(99)+n).slice(-`${l}`.length)).join` `

Does not require any input. Formatting was painful. If there was an upper limit on the amount of padding I could reduce (' '.repeat(99)+n) to something shorter e.g. ` ${n}`.

  • \$\begingroup\$ I think you can replace /[^]/g with /./g to save two bytes \$\endgroup\$ Commented Feb 27, 2016 at 16:24
  • \$\begingroup\$ @PatrickRoberts No, that skips newlines, so my count would be off. \$\endgroup\$
    – Neil
    Commented Feb 27, 2016 at 16:25
  • \$\begingroup\$ Ah, never noticed that before. \$\endgroup\$ Commented Feb 27, 2016 at 16:28

PowerShell, 140 bytes

"{0,$c} {1,$c} {2,$c}"-f$l,$w,$b

(newline left in for clarity :D)

The first line takes input $a, and then the next part is all one statement. We're setting $c equal to some-string's .length. This will form our requisite padding. Inside the string is an immediate code block $(...), so that code will be executed before evaluated into the string.

In the code block, we're sending three items through the |sort command, and then taking the biggest one (...)[-1]. This is where we're ensuring to get the columns to the correct width. The three items are $l the line count, where we -split on newlines, the $w word count, where we -split on whitespace, and $b the length.

The second line is our output using the -f operator (which is a pseudo-shorthand for String.Format()). It's another way of inserting expanded variables into strings. Here, we're saying that we want all of the output to be padded to the left so that each column is $c wide. The padding is done via spaces. The 0, 1, and 2 correspond to the $l, $w, and $b that are arguments to the format operator, so the line count, word count, and byte count are padded and output appropriately.

Note that this either requires the string to have already-expanded newlines (e.g., doing a Get-Content on a text file or something, and then either piping or saving that to a variable, then calling this code on that input), or use the PowerShell-styled escape characters with backticks (meaning `n instead of \n).


PS C:\Tools\Scripts\golfing> .\reimplement-wc.ps1 "This line`nis broken`ninto three lines.`n"
 3  7 38

C, 180 178 bytes

#include <stdio.h>
#include <ctype.h>
main(b,w,l,c,d){d=' ';b=w=l=0;while((c=fgetc(stdin))!=EOF){if(!isspace(c)&&isspace(d))w++;b++;d=c;if(c==10)l++;}printf("%d %d %d\n",l,w,b);}

Pip -s, 25 bytes


Takes the multiline string as a command-line argument. Try it online!

Thanks to Dennis's CJam answer for making me realize that the longest number is always the character count.


                           s is space; n is newline; a is 1st cmdline arg (implicit)
           [            ]  Construct a list of three elements:
            nNa             Number of newlines in a
               `\S+`Na      Regex search: number of runs of non-whitespace characters in a
                      #a    Length of a (i.e. number of characters in a)
          M                To each element of that list, map this function:
   #a                       Number of characters in a
  #                         Length of that number
     -#_                    Subtract length of each element
sX                          Construct a string of that many spaces
        ._                  Prepend it to the element
                           The resulting list is autoprinted, space-separated (-s flag)

Here's a 29-byte solution with flags -rs that takes input from stdin:


Try it online!


Powershell, 123 115 bytes

switch -r($args|% t*y){'\s'{$a=0}'\S'{$w+=!$a;$a=1}'(?s).'{$b++}'
"{0,$c} {1,$c} $b"-f$l,+$w

Test script:

$f = {

switch -r($args|% t*y){    # evaluate all matched cases
    '\s'   {$a=0}          # any whitespace (newline not included)
    '\S'   {$w+=!$a;$a=1}  # any not-whitespace (newline not included)
    '(?s).'{$b++}          # any char (newline included!)
    '`n'   {$l++}          # new line char
"{0,$c} {1,$c} $b"-f$l,+$w


    , ("a b c d`n", "1 4 8")
    , ("a b c d e f`n", " 1  6 12")
    , ("  a b c d e f  `n", " 1  6 16")
    , ("a`nb`nc`nd`n", "4 4 8")
    , ("a`n`n`nb`nc`nd`n", " 6  4 10")
    , ("abc123{}[]()...`n", " 1  1 16")
    , ("`n", "1 0 1")
    , ("   `n", "1 0 4")
    , ("`n`n`n`n`n", "5 0 5")
    , ("`n`n`na`nb`n", "5 2 7")
) | % {
    $s,$e = $_
    $r = &$f $s
    "$($e-eq$r): $r"


True: 1 4 8
True:  1  6 12
True:  1  6 16
True: 4 4 8
True:  6  4 10
True:  1  1 16
True: 1 0 1
True: 1 0 4
True: 5 0 5
True: 5 2 7


  • $args|% t*y splits arument strings into chars
  • switch -r($args|% t*y) evaluate all matched cases
    • '\s' case for any whitespace
    • '\S' case for any non-whitespace
    • '(?s).' case for any char (newline included)
    • '\n' case for newline char (newline represent itself)
  • $c="$b".Length calculate a length of bytes number. $b is always max($l,$w,$b) by design
  • "{0,$c} {1,$c} $b"-f$l,+$w format numbers with same length. The variable $w converts to int. It need for strings without words. Other variables formats 'as is' because 'The input will always contain a trailing newline' and $l and $b cannot be 0.
  • \$\begingroup\$ 104 bytes by using splatting, removing the quotes around '\s' and '\S', and replacing .Length with |% Le* \$\endgroup\$
    – Julian
    Commented Mar 6, 2023 at 2:36

Pascal, 248 bytes

This complete program requires a processor supporting “Extended Pascal” as defined by ISO standard 10206.

  • The variable input possesses the built-in data type text. As such any newline character (sometimes it’s CR, sometimes LF, sometimes CR+LF, or something else) is automagically converted into a single space character (' '). In order to distinguish from a space character as payload of a line, and a space character that resulted from this conversion, you will need to query the function EOLn.
  • A text variable is conceptually similar to a file of char. This program in fact counts characters, i. e. actually behaves like wc ‑m. However, since the task states that characters strictly draw from the ASCII character set, there is no difference.
program c(input,output);var l,w,c,z:integer value 0;p:char;begin p:=' ';while not EOF do begin c:=c+1;l:=l+ord(EOLn);w:=w+card([p]*[' ','   ']-[input^]);p:=input^;get(input)end;z:=trunc(ln(card([0..l,0..w,0..c]))/ln(10))+2;writeLn(l:z-1,w:z,c:z)end.

Ungolfed and annotated version:

{ By listing a `program` parameter of the spelling `input`,
  there’s an implicit `reset(input)` which implies a `get(input)`. }
program wordCount(input, output);
        { `line`, `word` and `character` are singular, because they kind
          of enumerate these units as if input was a zero-based `array`. }
        line, word, character, width: integer value 0;
        previousCharacter: char;
        { This program counts “word beginnings” as words. This is the
          _change_ from “space character” _to_ “non-space character”. }
        previousCharacter := ' ';
        while not EOF(input) do
            character := character + 1;
            { As per POSIX specification a line is payload _plus_ one newline. }
            line := line + ord(EOLn(input));
            { The second character literal is an HT (horizontal tabulator). }
            word := word + card([previousCharacter] * [' ', '   '] - [input^]);
            { Prepare `previousCharacter` for _next_ iteration. }
            previousCharacter := input^;
            { Advance “reading cursor”. }
        { To produce POSIX-compliant output write:
            writeLn(line:1, ' ', word:1, ' ', character:1);
          As per task specification we will determine a common width though.
          We use ⌊ln(N) / ln(10)⌋ + 1 as the base formula, where N needs to be
          the largest number from `line`, `word` and `character`. This can be
          found by the expression |[0, line] ∪ [0, word] ∪ [0, character] ∩ ℤ|.
          We add another +1 for the space _between_ numbers. }
        width := trunc(ln(card([0..line, 0..word, 0..character])) / ln(10)) + 2;
        writeLn(line:width-1, word:width, character:width);

Ruby, 108 bytes

a.map{|b|" "*(a.map(&:size).max-b.size)+b}*" "}

Perl, 71 62 61 bytes

includes +1 for -n

$;=length($b+=y///c);$w+=split$"}{printf"%$;d %$;d $b",$.,$w


while (<>) {                         # implicit because of -n
    $; = length(                     # printf formatting: width
       $b += y///c                   # count characters
    $w += split $"                   # count words
}{                                   # explicit: end while, begin END block
    printf "%$;d %$;d $b", $., $w    #  $. = $INPUT_LINE_NUMBER
}                                    # implicit because of -n
  • Save another byte, again thanks to @TonHospel.
  • Save 9 bytes thanks to @TonHospel showing me a few tricks of the trade!
  • \$\begingroup\$ A few tricks of the trade: Use y///c as a shorter length of $_. split$" in scalar context gives the number of words in $_. By using a punctuation variable like $; instead of $W you can put a d just after the interpolation in the format string. Then you can drop the d in $W and drop the parenthesis. And -p gains nothing over -n, just let the printf do the printing (add a newline to taste) \$\endgroup\$
    – Ton Hospel
    Commented Feb 26, 2016 at 14:34
  • \$\begingroup\$ Awesome, I appreciate it! \$\endgroup\$
    – Kenney
    Commented Feb 26, 2016 at 14:36
  • \$\begingroup\$ A calculation chain like $a=foo;$b=bar$a can usually be written as $b=bar($a=foo), saving one byte. Applicable here to $; and $b. You don't care if $; is recalculated every time \$\endgroup\$
    – Ton Hospel
    Commented Feb 26, 2016 at 15:26
  • \$\begingroup\$ Thanks! I overlooked that because there are two blocks... \$\endgroup\$
    – Kenney
    Commented Feb 26, 2016 at 16:05

Lua, 74 66 bytes




text = arg[1]
_,lines = text:gsub('\n','')
_,words = text:gsub('%S+','')
print(lines, words, text:len())

Receives input through command line arguments.

We rename the first argument (arg[1]) to save bytes. string.gsub returns the number of replacements as well as the modified string, so we're using that to count first '\n' (newlines), then '%S+' (instances of one or more non-whitespace characters, as many as possible, i.e. words). We can use anything we want for the replacement string, so we use the empty string ('') to save bytes. Then we just use string.len to find the length of the string, i.e. the number of bytes. Then, finally, we print it all.

  • \$\begingroup\$ I don't see any left padding of the lines and words values though \$\endgroup\$
    – Ton Hospel
    Commented Feb 27, 2016 at 2:09

Retina, 65

$#3 $#2 $.0
+`(\b(.)+ )(?!.*\b(?<-2>.)+$)

Try it Online!

The first stage is the actual wc program, the rest of it is for padding. The a placeholder thing is probably unnecessary, and some of the groups can probably be simplified a bit.


Haskell, 140 bytes

import Text.Printf
w h=let{l=length;s=show.l;c=s h;m=s.words$h;n=s.lines$h;f=maximum$map l[c, m, n];p=printf"%*s"f}in p n++' ':p m++' ':p c

The ungolfed version is hereunder, with expanded variable and function names:

import Text.Printf

wc str =
  let charcount = show.length $ str
      wordcount = show.length.words $ str
      linecount = show.length.lines $ str
      fieldwidth = maximum $ map length [charcount, wordcount, linecount]
      printer = printf "%*s" fieldwidth
  in printer linecount ++ (' ' : printer wordcount ++ (' ' : printer charcount))

This is a function that accepts a string and returns a string. It just uses the Prelude functions words (resp. lines) to get the number of words (resp. lines) given that they seem to use the same definition as wc, then gets the longest value (as a string) amongst the counts and use the printf format taking the width amongst its arguments for formatting.


05AB1E, 24 23 bytes


j is currently bugged, so could have been 21 bytes without the § and J..

Try it online or verify all test cases.


¨          # Remove the trailing newline of the (implicit) input
 ¶¡        # And split it on newlines
    S¡     # Take the first input again, and split it on [" \n\t"]
      õK   # Then remove all empty string items
¹          # And take the first input again as is
)          # Wrap all three value of the stack to a single list
 €g        # Take the length of each of the items
   §       # Cast the integers to strings (should have been implicit, but `j` is bugged)
    Z      # Take the max (always the last / amount of bytes) (without popping the list)
     g>    # Take the length + 1 of this max
       j   # Append leading spaces so all items or of this length
        J  # Join them together (should have been done by the `j` already, but it's bugged)
         ¦ # Remove the leading space (and output implicitly to STDOUT)

Ruby -p0, 79 bytes

Includes a trailing space in the output.

$_="%#{a.map{_1.to_s.size}.max}d "*3%a

Attempt This Online!

Ruby -p0, 84 bytes

No trailing space.

$_=["%#{a.map{_1.to_s.size}.max}d"]*3*" "%a

Attempt This Online!


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.