将数据存储在多个数组中(bash)

时间:2017-06-26 01:31:57

标签: arrays bash multidimensional-array

我试图将.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(newbie)的数组感到困惑。

1 个答案:

答案 0 :(得分: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