文件如下:
test
1
2
3
4
5
使用命令
- wc -l test
输出结果为
5 test
使用管道符计算文件行数脚本如下:
- #!/bin/sh
- linenum=0
- cat test | while read line
- do
- echo "line content: $line"
- ((linenum+=1))
- done
- echo "line number: $linenum"
输出结果为
line content: 1
line content: 2
line content: 3
line content: 4
line content: 5
line number: 0
使用重定向计算文件函数脚本如下:
- #!/bin/sh
- linenum=0
- while read line
- do
- echo "line content: $line"
- ((linenum+=1))
- done < test
- echo "line number: $linenum"
输出结果为
line content: 1
line content: 2
line content: 3
line content: 4
line content: 5
line number: 5
分析结果:
使用管道符时,会fork出一个子进程,变量在父子进程里无法互通。使用第二种方式,在同一个进程中,所以达到了我们预期的目的。
本文通过两种Shell脚本方法展示了如何统计文件中的行数。一种方法使用管道符但导致变量隔离,另一种则通过重定向成功实现了计数目的。
1043

被折叠的 条评论
为什么被折叠?



