简体   繁体   中英

Concatenate strings with delimeter in for loop in shell script

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

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

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.

I assume you want to temporarily assign IFS to "," not to affect the following codes. Then you can combine it with read command as follows:

#!/bin/bash

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

IFS=',' read -r -a list <<< "$1"
for item in "${list[@]}"; do
    ary+=( "${handles["$item"]}" )
done

result=$(IFS=','; echo "${ary[*]}")
echo "$result"
  • The for loop assigns the array ary to the values of the associative array handles keyed by the elements of list .
  • The command echo "${ary[*]}" concatenates the array ary with the delimiter , . It is executed in the subshell without modifying IFS in the foreground process.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM