簡體   English   中英

Bash數組:需要空白幫助

[英]Bash arrays: Need help with white space

我正在嘗試使用以下示例格式從文件中創建bash數組:

data, data, interesting
data, data, more interesting

我填充數組的方式:

read -r -a DATA1 <<< $(cat $FILE | awk -F, '{ print $1 }')
read -r -a DATA2 <<< $(cat $FILE | awk -F, '{ print $2 }')
read -r -a DATA3 <<< $(cat $FILE | awk -F, '{ print $3 }')

當我檢查數組DATA3時,有3個元素:

interesting
more
interesting

我需要它只顯示2個元素,如:

interesting
more interesting

如何保留字段3中的空白區域,這樣當我從數組中調用該元素時,它看起來“更有趣”? 有沒有更好的方法來處理這個?

關鍵是將IFS (內部字段分隔符)變量與read一起使用。

read可以使用-a選項將單詞直接讀入數組。 設置IFS=,它將以逗號分割:

while read f; do
    echo "$f" | (IFS=, && read -a arr && echo ${arr[2]})
done

會回應

interesting
 more interesting 

您還可以直接讀取變量名稱:

IFS=, && read f1 f2 f2

編輯:我可以推薦閱讀Advanced Bash Scripting Guide

使用cut 例:

read -r -a DATA1 <<< $(cut -d, -f 1 $FILE)
read -r -a DATA2 <<< $(cut -d, -f 2 $FILE)
read -r -a DATA3 <<< $(cut -d, -f 3 $FILE)
IFS=','
while read -a array
do
    echo "${array[2]}" 
done < data.csv
>> Is there a better way to handle this? - Tee Bone

$ awk -F", " '{print $3}' file
interesting
more interesting

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM