4

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?

0
5

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
1
  • Quick, easy, painless. Thanks for the cogent answer.
    – user9398
    Sep 22 '09 at 14:02
3

You can use an array.

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

value1
0

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'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.