Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I am looking for a quick/easy way to split a string in ksh.

It has varied number delimiters (spaces) between each item.

Example:

value1 value2                  value3

Any suggestions/advice?

share|improve this question
up vote 5 down vote accepted

Using a for loop with the input string will split on whitespace.

LIST="value1  value2 value3"
for x in $LIST ; do
    echo $x
done

Yields

value1
value2
value3

or

LIST="value1  value2 value3"
set -A STRING "$LIST"
for x in $STRING ; do
    echo $x
done

Yields

value1
value2
value3
share|improve this answer
    
Quick, easy, painless. Thanks for the cogent answer. – user9398 Sep 22 '09 at 14:02

You can use an array.

LIST="value1  value2 value3"
set -A values $LIST
echo ${values[0]}

value1
share|improve this answer

Piping through sed and optionally grep works too

LIST="value1  value2 value3" ;
echo "$LIST" | sed 's/[[:space:]]/\n/g' | grep .

You can drop the grep if you also drop the quotes which removes multiple spaces though other formatting may be effected.

LIST="value1  value2 value3" ;
echo $LIST | sed 's/[[:space:]]/\n/g'
share|improve this answer

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .