读行时在 bash 外求和

d9n*_*gle 3 bash pipe awk

我试图找出.js文件夹中文件的行数总和。我在 bash 中使用它:

sum=0 && find . | grep ".js" | while read -r f; do wc -l $f | awk '{print $1;}'; done;
Run Code Online (Sandbox Code Playgroud)

$sum += $1里面的awk不起作用。我该怎么做?

PS:我知道这可以更容易地实现使用

find . -name '*.js' | xargs wc -l
Run Code Online (Sandbox Code Playgroud)

我仍然想要上面的解决方案。

pLu*_*umo 11

试试这个简单且超快速的解决方案:

find . -type f -name "*.js" -exec cat {} + | wc -l
Run Code Online (Sandbox Code Playgroud)

wc之前尝试过一些解决方案,但它们会出现问题,例如文件名中的换行符和/或速度很慢。


gle*_*man 5

bash 在单独的子 shell 中执行管道的每个命令,除非您启用lastpipeshell 选项

# bash requires job control to be disabled for lastpipe setting
set +m
shopt -s lastpipe

declare -i sum=0
find . -name '*.js' -print0 | while IFS= read -d '' -r name; do
    (( sum += $(wc -l < "$name") ))   # redirect the file into wc for easier output
done
echo $sum
Run Code Online (Sandbox Code Playgroud)

进程替换对于处理这个 subshel​​l 问题很方便:

declare -i sum=0
while IFS= read -d '' -r name; do
    (( sum += $(wc -l < "$name") ))   # redirect the file into wc for easier output
done < <(
    find . -name '*.js' -print0
)
echo $sum
Run Code Online (Sandbox Code Playgroud)

然而,这使得程序流更难阅读。

  • 添加一些分号并删除换行符。为什么必须是一行? (3认同)

mar*_*raf 5

您想awk进行加法并显示结果吗?

awk '{sum +=$1} END {print sum}' 应该做的伎俩。

在我的 bash 脚本库中,我这样做:

$ find . -type f -name '*.bash' \
| while read -r f ; do wc -l "$f" ; done \
| awk '{sum +=$1} END {print sum}'
Run Code Online (Sandbox Code Playgroud)

并得到结果 522