Here's a hybrid perl/fold approach:
$ echo "The cat hopped in a box." | fold -w 1 |
perl -lne 'push @k, "$_ "; push @l,sprintf "%-2s",$.; END{print "@k\n@l"}'
T h e c a t h o p p e d i n a b o x .
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
Explanation
fold -w 1
: this will fold the input at a width of one character, resulting in each input character printed on a separate line.
perl -lne
: the -l
removes trailing newlines from the input and adds a newline to each print
call; the n
reads input line by line and the e
provides the script to run on it.
push @k, " $_";
: Add a space to the the current line ($_
) and save it in in the array @k
.
push @l,sprintf "%-2s",$.;
: sprintf
will return a formatted string, here we are giving it the current line number ($.
) and telling it to print it with spaces added as needed to make its length 2. The string is then added to the @l
array.
END{print "@k\n@l"}'
: once the whole file has been read, print the two arrays.
If you just need to number the characters and don't mind multi-line output, a simpler approach is (using a shorter string for brevity):
$ echo "foo bar" | fold -w1 | cat -n
1 f
2 o
3 o
4
5 b
6 a
7 r
od -c
to show numbered output. – slm♦ Oct 30 '14 at 13:30