Try:
$ echo 0,2,4-6,8 | awk '/-/{for (i=$1; i<=$2; i++)printf "%s%s",i,ORS;next} 1' ORS=' ' RS=, FS=-
0 2 4 5 6 8
This can be used in a loop as follows:
for n in $(echo 0,2,4-6,8 | awk '/-/{for (i=$1; i<=$2; i++)printf "%s%s",i,ORS;next} 1' RS=, FS=-)
do
echo cpu="$n"
done
Which produces the output:
cpu=0
cpu=2
cpu=4
cpu=5
cpu=6
cpu=8
Or like:
printf "%s" 0,2,4-6,8 | awk '/-/{for (i=$1; i<=$2; i++)printf "%s%s",i,ORS;next} 1' RS=, FS=- | while read n
do
echo cpu="$n"
done
Which also produces:
cpu=0
cpu=2
cpu=4
cpu=5
cpu=6
cpu=8
How it works
The awk command works as follows:
RS=,
This tells awk to use ,
as the record separator.
If, for example, the input is 0,2,4-6,8
, then awk will see four records: 0
and 2
and 4-6
and 8
.
FS=-
This tells awk to use -
as the field separator.
With FS
set this way and if, for example, the input record consists of 2-4
, then awk will see 2
as the first field and 4
as the second field.
/-/{for (i=$1; i<=$2; i++)printf "%s%s",i,ORS;next}
For any record that contains -
, we print out each number starting with the value of the first field, $1
, and ending with the value of the second field, $2
. Each such number is followed by the Output Record Separator, ORS
. By default, ORS
is a newline character. For some of the examples above, we set ORS
to a blank.
After we have printed these numbers, we skip the rest of the commands and jump to the next
record.
1
If we get here, then the record did not contain -
and we print it out as is. 1
is awk's shorthand for print-the-line.