#!/bin/sh
var='data1,data2,data3'
unset data
while [ "$var" != "$data" ]; do
data=${var%%,*} # delete first comma and the bit after it
var=${var#*,} # delete bit up to first comma (and the comma)
printf 'data = "%s"\n' "$data"
done
Here, we use variable substitutions to get each successive comma-delimited data field from the value of the var
variable. The first assignment to data
in the loop will remove everything from $var
after the first comma. The var
variable is then modified so that the first bit up to the first comma is deleted.
This continues until "$var" = "$data"
which means that nothing more can be done to the string.
This way of doing it would allow us to handle comma-separated data strings that contain embedded newlines:
var='line1
line2,data2,last bit
goes here'
With the above values in var
, the above script would output
data = "line1
line2"
data = "data2"
data = "last bit
goes here"
Not caring about embedded newlines; You very seldom have to loop over invocations of awk
.
Note that awk
is perfectly happy to read your string as a set of comma-delimited fields, and that it's able to loop over these:
printf '%s\n' "$var" |
awk -F ',' '{ for (i=1; i<=NF; i++) print $i }'
With var='data1,data2,data3'
, this would print
data1
data2
data3
Another shell solution that makes use of the IFS
variable to split the $var
value into bits while also using set -f
to disable filename expansion:
set -f
oldIFS=$IFS; IFS=','
set -- $var
IFS=$oldIFS; unset oldIFS
set +f
for data do
printf 'data = "%s"\n' "$data"
done
echo "${var//,/$'\n'}"
)