bash 文件列表上 awk 的文件大小总和

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21157833/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 09:16:23  来源:igfitidea点击:

Sum of file sizes with awk on a list of files

bashawk

提问by THX

I have a list of files and want to sum over their file sizes. So, I created a (global) variable as counter and are trying to loop over that list, get the file size with ls and cut&add it with

我有一个文件列表,想总结一下它们的文件大小。因此,我创建了一个(全局)变量作为计数器并尝试遍历该列表,使用 ls 获取文件大小并使用 cut&add

export COUNTER=1
for x in $(cat ./myfiles.lst); do ls -all $x | awk '{COUNTER+=}'; done

However, my counter is empty?

但是,我的柜台是空的?

> echo $COUNTER
> 1

Does someone has an idea for my, what I am missing here?

有人对我有什么想法,我在这里缺少什么?

Cheers and thanks, Thomas

干杯和感谢,托马斯



OK, I found a way piping the result from the awk pipe into a variable (which is probably not elegant but working ;) )

好的,我找到了一种将 awk 管道的结果传送到变量中的方法(这可能不优雅但有效;))

for x in $(cat ./myfiles.lst); do a=$(ls -all $x |awk '{print }'); COUNTER=$(($COUNTER+$a)) ; done

> echo $COUNTER
> 4793061514

回答by Zsolt Botykai

Because you are doing it wrong. Awk is called for every file, so in COUNTERyou got the last file's size.

因为你做错了。awk 为每个文件调用,所以COUNTER你得到了最后一个文件的大小。

A better solution is:

更好的解决方案是:

ls -all <myfiles.lst | awk '{COUNTER+=} END {print COUNTER}'

But you are reinventing the wheel here. You can do something like

但是你在这里重新发明轮子。你可以做类似的事情

du -s <myfiles.lst 

(If you have duinstalled. Note: see the comments below my answer about du. I had tested this with cygwinand with that it worked like a charm.)

(如果您已du安装。注意:请参阅我关于 的回答下方的评论du。我已经对此进行了测试,cygwin并且它的效果非常好。)

回答by Richard Lohman

Shorter version of the last:

上一个的简短版本:

ls -l | awk '{sum += } END {print sum}'

Now, say you want to filter by certain types of files, age, etc... Just throw the ls -l into a find, and you can filter using find's extensive filter parameters:

现在,假设您想按某些类型的文件、年龄等进行过滤……只需将 ls -l 放入 find 中,您就可以使用 find 的广泛过滤器参数进行过滤:

find . -type f -exec ls -l {} \; | awk '{sum += } END {print sum}'

回答by neeraj

ls -ltS | awk -F " " {'print '} | awk '{s+=} END {print s}'