Home > Software design >  Concatenate strings with delimeter in for loop in shell script
Concatenate strings with delimeter in for loop in shell script

Time:09-27

Adding comma creates a space instead of appending comma.

Note: Value of $1 is s,v,h

declare -A handles
handles["s"]="test1"
handles["v"]="test2"
handles["h"]="test3"

IFS=',' list=($1)
for item in "${list[@]}"; do
        result =",${handles["$item"]}"
done

echo -e $result

Output: test1 test2 test3

Expected: test1,test2,test3

CodePudding user response:

One idea to get around the issues with clobbering IFS, and eliminating unwanted commas from $result, ...

$ cat script.sh
#!/usr/bin/bash

declare -A handles
handles["s"]="test1"
handles["v"]="test2"
handles["h"]="test3"
handles["a b c"]="test 4"

mapfile -t list < <(tr ',' '\n' <<< "$1")     # to handle white space in fields

unset pfx

for item in "${list[@]}"
do
    handle="${handles[$item]}"

    # only append if non-empty
    [ -n "${handle}" ] && result ="${pfx}${handle}" && pfx=','
done

echo -e "${result}"

$ script.sh 's,v,h'
test1,test2,test3

$ script.sh 'a b c,s,v,h'
test 4,test1,test2,test3

$ script.sh 'd e f,s,v,h'
test1,test2,test3

$ script.sh 'x,y,z,s,v,h,a,b,c'
test1,test2,test3

CodePudding user response:

The IFS is the problem:

> x=",a" && x =",b" && x =",c" && echo $x
,a,b,c 
> IFS="," && x=",a" && x =",b" && x =",c" && echo $x
 a b c

Just add IFS="" before the echo or use echo -e "$result" and it will work.

  • Related