Question

I have a problem similar to the one solve in this question: How do I split a string on a delimiter in Bash? .

The real difference is that I'm targeting the sh and ksh shell so, for example, I can't use the <<< redirection.

To recap my problem I have the content of a variable that is

VALUES="
val1    ;val2    ;val3
another1;another2;another3
"

so clearly the whitespace and ; are the characters that I would like to get rid of.

I also have to use this values as they appear in a 3 by 3 basis, 3 at the time, but I assume that for that I can simply use $1,$2 and $3 after the expansion plus a shift 3 at the end of each cycle.

Thanks.

Was it helpful?

Solution

VALUES="
val1    ;val2    ;val3
another1;another2;another3
"
echo "$VALUES" | while IFS=' ;' read v1 v2 v3; do 
    [[ -z $v1 && -z $v2 && -z $v3 ]] && continue
    echo "v1=$v1  v2=$v2  v3=$v3"
done
v1=val1  v2=val2  v3=val3
v1=another1  v2=another2  v3=another3

Re-reading your question, you're talking about arrays. Here you go:

typeset -a values
typeset -i i=0
echo "$VALUES" | while IFS=' ;' read v1 v2 v3; do
    [[ -z $v1 && -z $v2 && -z $v3 ]] && continue
    values[i]=$v1
    values[i+1]=$v2
    values[i+2]=$v3
    ((i+=3))
done

for i in "${!values[@]}"; do printf "%d\t%s\n" $i "${values[i]}"; done
0   val1
1   val2
2   val3
3   another1
4   another2
5   another3

OTHER TIPS

You can use awk and reduce all the complexity:

echo "$VALUES"|awk -F' *; *' 'NF>1{print $1, $2, $3}'
val1 val2 val3
another1 another2 another3
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top