Reputation: 151
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;
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=>
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
Upvotes: 2
Views: 1027
Reputation: 45586
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
Upvotes: 3