通过忽略分隔符前后的空格来拆分逗号分隔的字符串,并存储在 shell 脚本中的数组中
Split comma separated string by ignoring spaces in front and back of delimiter and store in array in shell script
我需要帮助在 bash 脚本中使用分隔符“,”拆分字符串并忽略分隔符前后的空格。
My string looks like below and ',' is delimiter.
mystring = < hostname1, hostname 2 , hostname value 3 >
Notice that
1. 'hostname1' has extra space in front
2. 'hostname 2' and 'hostname value 3' have extra spaces in front/back
I want to split above string and store in array like below:
mystring[0]:hostname1
mystring[1]:hostname 2
mystring[2]:hostname value 3
Please see below code and output:
HOSTNAME="hostname1 , hostname 2 , hostname value 3 "
IFS=',' read -ra hostnames <<< "$(HOSTNAME)"
for (( i=0; i<=2; i++ ))
do
echo hostname:[${hostnames[i]}]
done
Output
hostname:[hostname1 ]
hostname:[ hostname 2 ]
hostname:[ hostname value 3 ]
尝试以下操作:
readarray -t hostnames <<< "$(awk -F, '{ for (i=1;i<=NF;i++) { gsub(/(^[[:space:]]+)|([[:space:]]+$)/,"",$i);print $i } }' <<< "$HOSTNAME")"
使用 awk,将字段分隔符设置为“,”,然后循环遍历每个字段,使用 gsub 删除字符串开头和结尾的空格,打印结果。然后将生成的输出重定向回 readarray 以创建主机名数组。
你会尝试以下方法吗:
str=" hostname1, hostname 2 , hostname value 3 "
IFS=, read -r -a ary < <(sed 's/^ *//; s/ *$//; s/ *, */,/g' <<< "$str")
for i in "${ary[@]}"; do echo "hostname[$i]"; done
输出:
hostname[hostname1]
hostname[hostname 2]
hostname[hostname value 3]
我需要帮助在 bash 脚本中使用分隔符“,”拆分字符串并忽略分隔符前后的空格。
My string looks like below and ',' is delimiter.
mystring = < hostname1, hostname 2 , hostname value 3 >
Notice that
1. 'hostname1' has extra space in front
2. 'hostname 2' and 'hostname value 3' have extra spaces in front/back
I want to split above string and store in array like below:
mystring[0]:hostname1
mystring[1]:hostname 2
mystring[2]:hostname value 3
Please see below code and output:
HOSTNAME="hostname1 , hostname 2 , hostname value 3 "
IFS=',' read -ra hostnames <<< "$(HOSTNAME)"
for (( i=0; i<=2; i++ ))
do
echo hostname:[${hostnames[i]}]
done
Output
hostname:[hostname1 ]
hostname:[ hostname 2 ]
hostname:[ hostname value 3 ]
尝试以下操作:
readarray -t hostnames <<< "$(awk -F, '{ for (i=1;i<=NF;i++) { gsub(/(^[[:space:]]+)|([[:space:]]+$)/,"",$i);print $i } }' <<< "$HOSTNAME")"
使用 awk,将字段分隔符设置为“,”,然后循环遍历每个字段,使用 gsub 删除字符串开头和结尾的空格,打印结果。然后将生成的输出重定向回 readarray 以创建主机名数组。
你会尝试以下方法吗:
str=" hostname1, hostname 2 , hostname value 3 "
IFS=, read -r -a ary < <(sed 's/^ *//; s/ *$//; s/ *, */,/g' <<< "$str")
for i in "${ary[@]}"; do echo "hostname[$i]"; done
输出:
hostname[hostname1]
hostname[hostname 2]
hostname[hostname value 3]