Dedicated to all BASH newbies and Linux one liner lovers. Useful AWK,SED,BASH one liners.

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'

0 comments:

UNIX BASH scripting Headlines

© Jadu Saikia http://unstableme.blogspot.com