8. shell將字符串以逗號分割轉成數組(借助IFS)

原理是將變化shell環境下的一個系統變量IFS

#!/bin/bash

function to_array()

{

x=$1

OLD_IFS="$IFS" #默認的IFS值為換行符

IFS=","

array=($x) ?#以逗號進行分割了

IFS="$OLD_IFS" #還原默認換行符

for each in ${array[*]}

do

echo $each

done

}

arr=($(to_array 'a,b,c,d,e'))

echo ${arr[*]}

參考:shell分割字符串為數組


另外一個例子,介紹IFS的用法。參考shell中的特殊變量IFS

比如,有個文件內容如下:

? ? ? the first line.

the second line.

the third line.

打印每行:

forline in `cat filename`

do

echo $line

done

結果是下面這種一行一個單詞,顯然是不符合預期的:

the

first

line.

the

second

line.

the

third

line.


借助IFS變量進行做個調整:

IFS=$'\n'

for line in `cat k.shfile`

do

echo $line

done

輸出就是正確的:

? ? the first line.

the second line.

the third line.

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容