Search code examples
stringshellawkvertical-alignmentalignment

Making horizontal String vertical shell or awk


I have a string

ABCDEFGHIJ

I would like it to print.

A
B
C
D
E
F
G
H
I
J

ie horizontal, no editing between characters to vertical. Bonus points for how to put a number next to each one with a single line. It'd be nice if this were an awk or shell script, but I am open to learning new things. :) Thanks!


Solution

  • If you just want to convert a string to one-char-per-line, you just need to tell awk that each input character is a separate field and that each output field should be separated by a newline and then recompile each record by assigning a field to itself:

    awk -v FS= -v OFS='\n' '{$1=$1}1'
    

    e.g.:

    $ echo "ABCDEFGHIJ" | awk -v FS= -v OFS='\n' '{$1=$1}1'
    A
    B
    C
    D
    E
    F
    G
    H
    I
    J
    

    and if you want field numbers next to each character, see @Kent's solution or pipe to cat -n.

    The sed solution you posted is non-portable and will fail with some seds on some OSs, and it will add an undesirable blank line to the end of your sed output which will then become a trailing line number after your pipe to cat -n so it's not a good alternative. You should accept @Kent's answer.