[英]Concatenate strings with delimeter in for loop in shell script
添加逗號會創建一個空格而不是附加逗號。
注: $1
的值為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
test1 test2 test3
: 測試 1 測試 2 測試 3
預期: test1,test2,test3
一個解決問題的想法是破壞IFS
,並從$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
IFS
是問題所在:
> x=",a" && x+=",b" && x+=",c" && echo $x
,a,b,c
> IFS="," && x=",a" && x+=",b" && x+=",c" && echo $x
a b c
只需在echo
前添加IFS=""
或使用echo -e "$result"
。
我假設您想暫時將IFS
分配給“,”而不影響以下代碼。 然后你可以將它與read
命令結合起來,如下所示:
#!/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"
for
循環將數組ary
分配給由list
的元素鍵控的關聯數組handles
的值。echo "${ary[*]}"
將數組ary
與定界符,
連接起來。 它在子shell中執行,無需修改前台進程中的IFS
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.