在读取文件bash时,将单词分割成数组

时间:2020-11-25 18:30:26

I have a file that contains multiple words with commas. I want to read a file and store these words into array. In this file, first line is header, the other lines are datum. But some datum are null.So, this null characters need to be 0 For instance;

我有一个包含多个带逗号的单词的文件。我想读取一个文件并将这些单词存储到数组中。在这个文件中,第一行是header,其他行是datum。但是有些数据是空的。比如,这个空字符必须是0;

H1;H2;H3;H4   
12;23;33;44   
44;;7;8   
13;;;9  

So I want to skip first line and put datum into 4 array=>

我想跳过第一行把数据放到4个数组=>中

H1 array= 12;44;13  
H2 array= 23;0;0  
H3 array= 33;7;0  
H4 array= 44;8;9  

So my code is like that:

我的代码是这样的

array=()
awk 'NR>1' $filename2 | while read line
do
    cntr=0
    IFS=";"
    for i in $line; do
        if [ -z $i ]; then array[cntr]=0; 
           else array[cntr]=$i;
        fi
    cntr=$[$cntr +1]
    done
    h1array+=("${array[0]}")
    h2array+=("${array[1]}")
    h3array+=("${array[2]}")
    h4array+=("${array[3]}")
done
for ((i=0;i<3;i++)); do
    echo "${h1array[$i]}"
done
for ((i=0;i<3;i++)); do
    echo "${h2array[$i]}"
done
for ((i=0;i<3;i++)); do
    echo "${h3array[$i]}"
done
for ((i=0;i<3;i++)); do
    echo "${h4array[$i]}"
done

So,it prints null in terminal. How can I do this? Thank you

它在终端上输出null。我该怎么做呢?谢谢你!

1 个解决方案

#1


3  

Is this what you are after?

这就是你想要的吗?

#!/bin/bash

while read -r line; do
        [[ "${line}" == *';'* ]] || continue
        IFS=';' read -r h1 h2 h3 h4 <<< "${line}"
        h1array+=("${h1:-0}")
        h2array+=("${h2:-0}")
        h3array+=("${h3:-0}")
        h4array+=("${h4:-0}")
done < <(tail -n +2 input.txt)

echo "h1array = ${h1array[@]}"
echo "h2array = ${h2array[@]}"
echo "h3array = ${h3array[@]}"
echo "h4array = ${h4array[@]}"

.

$ ./t.sh
h1array = 12 44 13
h2array = 23 0 0
h3array = 33 7 0
h4array = 44 8 9

#1


3  

Is this what you are after?

这就是你想要的吗?

#!/bin/bash

while read -r line; do
        [[ "${line}" == *';'* ]] || continue
        IFS=';' read -r h1 h2 h3 h4 <<< "${line}"
        h1array+=("${h1:-0}")
        h2array+=("${h2:-0}")
        h3array+=("${h3:-0}")
        h4array+=("${h4:-0}")
done < <(tail -n +2 input.txt)

echo "h1array = ${h1array[@]}"
echo "h2array = ${h2array[@]}"
echo "h3array = ${h3array[@]}"
echo "h4array = ${h4array[@]}"

.

$ ./t.sh
h1array = 12 44 13
h2array = 23 0 0
h3array = 33 7 0
h4array = 44 8 9