Arrays 未将值分配给数组元素Bash脚本
我正在写下面的脚本Arrays 未将值分配给数组元素Bash脚本,arrays,bash,script,Arrays,Bash,Script,我正在写下面的脚本 我不明白为什么我不能给数组赋值,当我打印数组元素时,我只得到arr[0],其余的元素都是空的 有没有更有效的方法来匹配从rt_事实文件中提取的字段rt_h和rt_f之间的l_num $bash-版本 GNUBash,版本4.1.2(1)-发行版(x86_64-redhat-linux-GNU) 以下是过滤后的文件: $cat filtered_file 12 4046580009982686 05072021 24692161126100379438583 44442 5
$cat filtered_file
12 4046580009982686 05072021 24692161126100379438583 44442
54 4046580009982686 05072021 24692161126100379438583 44442
95 4046580009982686 05072021 24692161126100379438583 44442
在这个脚本中,我试图使用原始文件中的行号匹配过滤文件中的字符串
bash-4.1$vi comb\u rt\u ct.ksh
#!/bin/bash
rows=1
cols=$(($(cat rt_facts | wc -l) + 1))
declare -a arr #=( $(for i in {1..$cols}; do echo 0; done) )
echo "cols " $cols
for l_num in $(grep '4046580009982686 05072021 24692161126100379438583 44442' filtered_file | cut -d" " -f 1)
do
arr[0]="4046580009982686 05072021 24692161126100379438583 44442"
echo "l_num " $l_num
cat rt_facts | while IFS=" " read -r lineStr
do
line=( $lineStr )
#echo ${line[*]}
rt_h=$(echo ${line[2]} | cut -d":" -f 1)
rt_f=$(echo ${line[3]} | cut -d":" -f 1)
if (( l_num > $rt_h && l_num < $rt_f )); then
echo "rt_h rt_f " $rt_h " " $rt_f
echo "line[*] " ${line[*]}
i=${line[1]}
echo "i " $i
if [[ -z "${arr[$i]}" ]]; then
echo "empty"
arr[$i]=0
fi
(( arr[$i]++ ))
echo "arr[$i] "${arr[$i]}
#echo ${line[0]}
break
fi
done
echo
done
echo ${arr[@]}
echo ${arr[*]}
echo ${arr[2]}
bash-4.1$正如@glennjackman所指出的,需要对问题进行更新,以提供一个最小的、可重复的示例;因此,我不再尝试对脚本的意图进行反向工程(或找出名为
filtered\u file
的文件的内容),而是将重点放在一个感兴趣的项目上:
cat t_facts | while IFS=" " read
...
<assign_values_to_array>
...
done
解决此问题的一种方法应适用于
ksh
和bash
:
while IFS=" " read
...
<assign_value_to_array>
...
done < t_facts
而IFS=”“读取
...
...
完成
这消除了子shell调用,因此允许在主进程中进行新的数组分配
同样,我没有试图理解脚本的整体逻辑,但是fwiw。。。我建议OP将建议的代码更改为
while
循环(以消除子shell调用),以查看arr[]
数组是否填充了所需的结果。将脚本粘贴到脚本的扩展名为ksh
,扩展名为bash
shebang,您正在使用sh
运行它。我已经添加了过滤文件。Ksh扩展不是问题所在,但我已将其更新为.sh扩展。此建议适用于#1问题。非常感谢。你对#2有什么建议吗?
cat t_facts | while IFS=" " read
...
<assign_values_to_array>
...
done
arr[0]="4046580009982686 05072021 24692161126100379438583 44442"
while IFS=" " read
...
<assign_value_to_array>
...
done < t_facts