Shell分割迭代字符串

问题:

IN=”www:wangliang:hello”以冒号分隔,读取分割的内容www,wangliang和hello。

解答

前言

如果是是一空格(空白)为分隔符,下面是一种解决方案:

sentence="This is a sentence."
for word in $sentence
do
        echo $word
done

如果是要求直接读取,不迭代,下面是一种解决方案:
line=www:wangliang:hello
read p1 p2 p3 <<< (IFS=":";echo line)
echo p1, p2, p3

以下是多种方法:

solution 1

IFS=':' read -ra ADDR <<< "$IN"

#printf "%s\n" "${ADDR[@]}"
#echo "[" ${ADDR[0]} "]" "[" ${ADDR[1]} "]" "[" #${ADDR[2]} "]"

for i in "${ADDR[@]}"; do
    echo $i
done

solution 2

for i in $(echo $IN | tr ":" "\n")
do
  echo $i
done

solution 3

arrIN=(${IN//:/ })
# printf "%s\n" "${arrIN[@]}"
echo "[" ${arrIN[0]} "]" "[" ${arrIN[1]} "]" "[" ${arrIN[2]} "]"

solution 4

echo $IN | sed -e 's/:/\n/g'

solution 5

read ADDR1 ADDR2 ADDR3 <<<$(IFS=":"; echo $IN)
echo $ADDR1 "----" $ADDR2 "---" $ADDR3

你可能感兴趣的:(shell)