2017-06-26 33 views
0

我試圖在bash中的兩組數組中存儲一個.txt文件的內容。該文件是給定數據文件的特徵列表,由豎線(|)分隔。到目前爲止,我已經編寫了讀取文件的代碼,並分別打印每行數據,每行都跟隨該行的給定部分。將數據存儲在多個數組中(bash)

#prints line of text and then separated version 
while IFS='' read -r line || [[ -n "$line" ]] 
do 
    echo "Text read from file: $line" 
words=$(echo $line | tr "|" "\n") 
for tests in $words 
do 
    echo "> $tests" 
done 
done < "$1" 

輸出示例:

Text read from file: this|is|data|in|a|file 
> this 
> is 
> data 
> in 
> a 
> file 
Text read from file: another|example|of|data 
> another 
> example 
> of 
> data 

是否有辦法讓我數據的每個單獨的線存儲在一個陣列中,然後它的分解部分內的另一?我想這可能是使用循環,但我很困惑數組使用bash(新手)。

+1

你可能會對此都錯了 - 見[爲什麼 - 是 - 使用 - 一個殼 - 環 - 到 - 過程 - 文本視爲-bad實踐](https://unix.stackexchange.com/questions/169716/why-is-using-a-shell-loop-to-process-text-considered-bad-practice)。 –

回答

1

好的 - 我剛剛讀完像你所做的那樣的行,並將它們追加到lines陣列中。然後,像您那樣使用tr,並將其附加到words陣列。只需使用括號將它們標記爲在分配數組元素:

$ cat data.txt 
this|is|data|in|a|file 
another|example|of|data 

$ cat read_data.sh 
#!/bin/bash 
declare -a lines 
declare -a words 
while IFS='' read -r line || [[ -n "$line" ]] 
do 
    echo "Text read from file: $line" 
    lines+=($line) 
    words+=($(echo $line | tr "|" " ")) 
done < "$1" 

for ((ii=0; ii<${#lines[@]}; ii++)); do 
    echo "Line $ii ${lines[ii]}" 
done 

for ((ii=0; ii<${#words[@]}; ii++)); do 
    echo "Word $ii ${words[ii]}" 
done 

$ $ ./read_data.sh data.txt 
Text read from file: this|is|data|in|a|file 
Text read from file: another|example|of|data 
Line 0 this|is|data|in|a|file 
Line 1 another|example|of|data 
Word 0 this 
Word 1 is 
Word 2 data 
Word 3 in 
Word 4 a 
Word 5 file 
Word 6 another 
Word 7 example 
Word 8 of 
Word 9 data 
+0

你也可以用bask替換詞:單詞+ =($ {line // | /}) – grail

+0

太棒了!非常感謝。當兩個特徵之間存在空格時(在相同的分隔符內),我的數據打破了一些問題。例如:| 2017-06-20 11:16:39.103 |分成兩個「Word」和「Line」索引。如何避免這種情況的任何提示,而不是刪除兩個特徵之間的空間? – WashU

+0

是的。由於字段分隔符是一個管道,因此使用空格交換管道:'words + =($(echo $ line | tr「|」「|」))''。現在,有空格的單詞將會有管道。在顯示單詞的循環中,添加以下這行以將管道更改回空格(按照聖盃的建議):'words [ii] =「$ {words [ii] // | /}」 – Jack