Skip to main content

Split string using IFS [Resolved]

I have written a sample script to split the string but it is not working as expected

#!/bin/bash
IN="One-XX-X-17.0.0"
IFS='-' read -r -a ADDR <<< "$IN"
for i in "${ADDR[@]}"; do
 echo "Element:$i"
done
#split 17.0.0 into NUM
IFS='.' read -a array <<<${ADDR[3]};
for element in "${array[@]}"
do
    echo "Num:$element"
done

output

One
XX
X
17.0.0
17 0 0

but I expected the output to be:

      One
      XX
      X
      17.0.0
      17
      0
      0

Question Credit: user112232
Question Reference
Asked October 11, 2017
Posted Under: Unix Linux
8 views
4 Answers

Here my way:

OIFS=$IFS
IFS='-'
IN="One-XX-X-17.0.0"
ADDR=($IN)
for i in "${ADDR[@]}"; do
 echo "Element:$i"
done
IFS='.'
array=(${ADDR[3]})
for element in "${array[@]}"
do
  echo "Num:$element"
done

result as expected:

Num:17
Num:0
Num:0

credit: tonioc
Answered October 11, 2017
 
interesting, thanks. – tonioc 4 hours ago
 CanDoerz  1 week ago
 
In general, try to avoid "saving" IFS and setting it globally. You really only want to change the value of IFS for when $IN is expanded, and you also don't want pathname expansion performed on the expansion. Further, OIFS=$IFS doesn't distinguish between the cases when IFS was set to an empty string, and when IFS was completely unset. – chepner 19 hours ago
 CanDoerz  1 week ago
 
correct, thanks for update! – tonioc 21 hours ago
 CanDoerz  1 week ago
 
That $IN is invoking the split+glob operator. Here, you don't want the glob part (try on IN=*-*-/*-17.0.0 for instance), so you'd want to do set -o noglob before invoking it. See my answer for details. – Stéphane Chazelas 23 hours ago
 CanDoerz  1 week ago
Your Answer
D:\Adnan\Candoerz\CandoProject\vQA