我对来自文件的整数的总和在Bash shell中的计算存在问题。我想求和的整数位于每行awk($ NF)的最后一个字段中。
从技术上讲,这是我的Bash命令:
sum=0
for i in $(grep 'number_vars' file.txt | sed 's/_//g;s/,/./g;s/\.00//g' | awk '{print $NF}'); do sum=$((sum+i)); done
不幸的是,最后一条命令产生了一个错误:syntax error: invalid arithmetic operator
我不明白为什么。
因此,我继续尝试通过将所有整数存储到文件中来修复此错误temp.dat
:
for i in $(grep 'numbers_vars' file.txt | sed 's/_//g;s/,/./g;s/\.00//g' | awk '{print $NF}'); do echo $i >> temp.dat; done
我得到以下内容temp.dat
:
$ cat temp.dat
500
110
300
110
110
110
1500
110
1500
110
110
110
3000
110
110
110
3000
3000
110
110
然后,如果我这样做:
sum=0
for i in $(cat temp.dat); do sum=$((sum+i)); done
总是一样的错误: syntax error: invalid arithmetic operator
我也尝试过:sum=$(($sum+$i))
但是没有成功。
我现在不知道该怎么办。
更新1: WILSON对应于姓氏:
$ LC_ALL=C cat -vt file_in.txt | grep WILSON
WILSON PETER "^I^I500,00^M
WILSON PETER MR WILSON J MR WILSON PETER "^I^I110,00^M
WILSON PETER "^I^I300,00^M
MR WILSON CHRISTOPHE VIREMENT S ^M
WILSON PETER MR WILSON J MR WILSON PETER "^I^I110,00^M
MR WILSON CHRISTOPHE VIREMENT S ^M
WILSON PETER MR WILSON J MR WILSON PETER "^I^I110,00^M
WILSON PETER MR WILSON J MR WILSON PETER "^I^I110,00^M
WILSON PETER "^I^I1_500,00^M
WILSON PETER MR WILSON J MR WILSON PETER "^I^I110,00^M
WILSON PETER "^I^I1_500,00^M
WILSON PETER MR WILSON J MR WILSON PETER "^I^I110,00^M
WILSON PETER MR WILSON J MR WILSON PETER "^I^I110,00^M
WILSON PETER MR WILSON J MR WILSON PETER "^I^I110,00^M
WILSON PETER "^I^I3_000,00^M
...
更新2:解决方案我发现了如何获取格式良好的文本文件(.txt),即,每行对应于初始Excel表中一行的文件。我必须得出结论,我的MacOS Catalina上的Excel 2019导出工具确实是胡说八道:我意识到,通过编辑生成的文本文件,混合了所有内容,即一行可能是Excel表整行的一部分,等等。最后,这种格式不好,我什么也做不了。
解决方案:如果它可以帮助想要快速处理带有bash函数的Excel表的人,那么我做不到。
1) First export the Excel table to a PDF file
2) Open PDF file with Acrobat and export it to "raw text"
3) Then, I can check with `vim` is well formatted, i.e "a line in Excel table" equal to "one line in text file
4) After this checking, you can apply the different solutions suggested by all the people who helped me to compute the sum of the desired column.
For example, by following the procedure above from 1) to 4), I have just to do :
awk '{sum+=$2}END{print sum}' file.txt
最后,不要忘记这不是关于我的终端命令的问题,这是正确的,而是关于Excel生成的错误文本文件的问题。
因此,我找到了一种使用中介工具(Acrobat)来规避此问题的方法。我同意这有点棘手,但是我没有用唯一的Excel文本导出工具来做得更好。
从您的temp.dat
文件中,您可以尝试:
awk '{s+=$1} END {print s}' temp.dat
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句