如何解决如何计算一行中的值数量并将总计数存储到数组
我有一个场景,我想逐行获取所有值的计数并将其存储到动态数组中
文件中的数据:
"A","B","C","B"
"P","W","R","S"
"E","U","S"
"Y","F","C"
第一行: 4 -> 值
第二行: 4 -> 值
第三行: 4 -> 值
第四行: 3 -> 值
预期输出: 存储到数组: array_list=(4,4,3)
写了一个脚本但不起作用
array_list=()
while read -r line
do
var_comma_count=`echo "$line" | tr -cd,| wc -c`
array_list=+($( var_comma_count))
done < demo.txt
当我打印数组时,它应该给我所有值: echo "{array_list[@]}"
注意: 该文件可能最后包含不应读取的空行
当我计算文件时,它给了我计数:5,它应该忽略最后一行是空的
当我使用 awk 时,它给了我正确的计数:awk '{print NF}' demo.txt -> 4
我知道使用 while 循环处理文件不是最佳做法,但任何更好的解决方案将不胜感激
解决方法
也许使用 awk 可能更容易,将 FS 设置为逗号并检查字段数是否大于 0:
#!/bin/bash
array_list=($(awk -v FS=,'NF>0 {print NF}' demo.txt))
echo "${array_list[@]}"
输出
4 4 4 3
awk 命令解释:
awk -v FS=,' # Start awk,set the Field Separator (FS) to a comma
NF>0 {print NF} # If the Number of Fields (NF) is greater than 0,print the NF
' demo.txt # Close awk and set demo.txt as the input file
另一个选项可能是首先匹配整行的格式。如果匹配,则至少出现一次。
然后用逗号分隔该行。
array_list=($(awk '/^"[A-Z]"(,"[A-Z]")*$/{print(split($0,a,","));}' demo.txt))
echo "${array_list[@]}"
输出
4 4 4 3
awk 命令解释:
awk '/^"[A-Z]"(,"[A-Z]")*$/{ # Regex pattern for the whole line,match a single char A-Z between " and optionally repeat preceded by a comma
print(split($0,")); # Split the whole line `$0` on a comma and print the number of parts
}
' demo.txt
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。