如果我们要计算一个文本文件中某一列数字的总和,给出一个文件如下:
touch test.txt
1 3
2 4
3 5
4 7
使用之前提到的awk指令,可以使用以下方式:
awk '{s+=$2} END {print s}' test.txt
19
使用这种方式可以得到我们想要的结果,但是我们还可以使用另外一种方式:即使用shell脚本进行逐行处理。
接下来我们来剖析使用shell 脚本逐行处理文本求和
touch test.sh
#!/bin/bash
sum=0
cat test.txt | while read line
do
temp_num=$(echo "$line" | cut -d ' ' -f 2)
sum=$(( $sum + $temp_num ))
done
echo "we get sum:$sum"
$ chmod +x test.sh
$ ./test.sh
$ we get sum:0
得到的结果是0,显然是错误的
从脚本中分析,在cat test.txt 之后将数据通过管道传递到while循环中,而while 循环的执行结果都是在一个子shell中,一旦这个子shell退出后,它里面的执行结果就会被释放。
我们在Linux中可以安装shellcheck 工具,用于检查shell 脚本的正确性,以Ubuntu为例:
sudo apt-get install shellcheck
$ shellcheck 2.sh
In 2.sh line 3:
cat test.txt | while read line
^------^ SC2002: Useless cat. Consider 'cmd < file | ..' or 'cmd file | ..' instead.
^--^ SC2162: read without -r will mangle backslashes.
In 2.sh line 6:
sum=$(( $sum + $temp_num ))
^-^ SC2030: Modification of sum is local (to subshell caused by pipeline).
^--^ SC2004: $/${} is unnecessary on arithmetic variables.
^-------^ SC2004: $/${} is unnecessary on arithmetic variables.
In 2.sh line 9:
echo "we get sum:$sum"
^--^ SC2031: sum was modified in a subshell. That change might be lost.
For more information:
https://www.shellcheck.net/wiki/SC2030 -- Modification of sum is local (to ...
https://www.shellcheck.net/wiki/SC2031 -- sum was modified in a subshell. T...
https://www.shellcheck.net/wiki/SC2162 -- read without -r will mangle backs...
不使用管道命令的情况下,继续进行尝试
!/bin/bash
sum=0
for line in $(cat test.txt)
do
echo "we get line: $line"
temp_num=$(echo "$line" | cut -d ' ' -f 2)
sum=$(( $sum + $temp_num ))
done
echo "we get sum:$sum"
得到以下结果:
$ ./2.sh
we get line: 1
we get line: 3
we get line: 2
we get line: 4
we get line: 3
we get line: 5
we get line: 4
we get line: 7
we get sum:29!/bin/bash
IFS=