0

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!

jeffpkamp
  • 2,732
  • 2
  • 27
  • 51
  • http://stackoverflow.com/questions/8563745/loop-over-characters-in-input-string-using-awk – Eli Rose Aug 18 '13 at 01:53
  • thanks, I also figured this out on my own after a lot of messing. – jeffpkamp Aug 18 '13 at 03:52
  • @EliRose - the answer accepted in the question you reference has errors on almost every line, all of then newbie mistakes. You shouldn't provide it as a reference. – Ed Morton Aug 18 '13 at 14:17
  • @user2348290 - the "solution" you figured out does not produce the output you requested (it adds an extra line) and will fail on some systems so I wouldn't use that. – Ed Morton Aug 18 '13 at 14:20

5 Answers5

4

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.

Ed Morton
  • 188,023
  • 17
  • 78
  • 185
3

awk one-liner:

awk 'BEGIN{FS=""}{for(i=1;i<=NF;i++)print i,$i}'

test :

kent$  echo "ABCDEF"|awk 'BEGIN{FS=""}{for(i=1;i<=NF;i++)print i,$i}'                                                                                                       
1 A
2 B
3 C
4 D
5 E
6 F
Kent
  • 189,393
  • 32
  • 233
  • 301
1

So I figured this one out on my own with sed.

 sed 's/./&\n/g' horiz.txt > vert.txt
jeffpkamp
  • 2,732
  • 2
  • 27
  • 51
1

One more awk

echo "ABCDEFGHIJ" | awk '{gsub(/./,"&\n")}1'
A
B
C
D
E
F
G
H
I
J
Jotne
  • 40,548
  • 12
  • 51
  • 55
  • That has the same problem that the similar posted sed scripts have in that it will add a trailing blank line to the end of the output. – Ed Morton Aug 19 '13 at 13:02
0

This might work for you (GNU sed):

sed 's/\B/\n/g' <<<ABCDEFGHIJ

for line numbers:

sed 's/\B/\n/g' <<<ABCDEFGHIJ | sed = | sed 'N;y/\n/ /'

or:

sed 's/\B/\n/g' <<<ABCDEFGHIJ | cat -n
potong
  • 55,640
  • 6
  • 51
  • 83