2

I want to convert string (eg: abcdef) to a column

This is what I want.

a
b
c
d
e
f

I know how to covert string to column by using sed

$ echo abcdef | sed 's/[^.]/&\n/g'|sed '$d'

But how to covert it using awk?

Arjun Mathew Dan
  • 5,240
  • 1
  • 16
  • 27
binbjz
  • 821
  • 11
  • 15

3 Answers3

3
[akshay@localhost tmp]$ awk -v ORS= 'gsub(/./,"&\n")' <<<"abcdefgh"
a
b
c
d
e
f
g
h
Akshay Hegde
  • 16,536
  • 2
  • 22
  • 36
  • 1
    This prints an extra line at the end. – 123 Jun 30 '15 at 11:00
  • 1
    Just add `-v ORS=` to avoid adding a trailing newline: `awk -v ORS= 'gsub(/./,"&\n")'`. FYI the posted solutions that rely on setting`FS=""` are gawk-specific while this will work in any awk. – Ed Morton Jun 30 '15 at 16:26
2

You can set the field separator to an empty string, so that every character is a different field. Then, loop through them and print:

$ awk -v FS="" '{for (i=1;i<=NF;i++) print $i}' <<< "abcdef"
a
b
c
d
e
f

Which is equivalent to:

awk -F "" '{for (i=1;i<=NF;i++) print $i}' <<< "abcdef"
Community
  • 1
  • 1
fedorqui
  • 275,237
  • 103
  • 548
  • 598
  • 1
    You can also use split, but you need to make sure to control awk's sorting (by default it is unsorted): `awk 'BEGIN {PROCINFO["sorted_in"]="@ind_str_asc"} {split ($0,arr,"");for (i in arr){print arr[i]}}' <<< "abcdefg"` –  Apr 08 '16 at 21:39
0

Only working with awks internal variables:

echo abcdef | awk 'BEGIN{FS="";OFS="\n"}{$1=$1}1'

It sets the input field separator (FS) to nothing which means that every character is a field. The output field separator (OFS) is set to newline. Notive the $1=$1 is needed to rebuild the record with the new OFS.

chaos
  • 8,162
  • 3
  • 33
  • 40