Wednesday, July 8, 2009

Split a string to characters in Bash


Input string:

1234 5678

o/p required:

1
2
3
4

5
6
7
8


Using -w option of Linux fold (wrap each input line to fit in specified width)

$ echo "1234 5678" | fold -w1

Awk solution : Make field separator (FS) as NULL so that each character represents a field

$ echo "1234 5678" | awk 'BEGIN{FS=""}{for(i=1;i<=NF;i++)print $i}'

Using bash:

#!/bin/sh

str="1234 5678"
while [ -n "$str" ]
do
printf "%c\n" "$str"
str=${str#?}
done


Using sed (Using & as matched string)

$ echo "1234 5678" | sed 's/[0-9 ]/&\n/g'

2 comments:

Paul Dorman said...

cat "1234 5678"|grep -o -P "."

or

grep -o -P "."

Jadu Saikia said...

@Paul Dorman, thanks for the solution using perl regexp with grep.
-o is a very useful option with grep to print only the matching part.

© Jadu Saikia www.UNIXCL.com