如何使用 find 命令仅打印出名称和文件大小?
How can I print out only the name and file size using the find command?
所以我有这个有效的命令行。
find . -type f |xargs ls -lS |head -20
问题是我只想输出文件大小和名称。我试过了:
find . -type f -printf '%s %p\n' |xargs ls -lS |head -20
但这给了我一堆 'cannot access [inode], no such file or directory' 错误。
我的目标是打印目录中最大的 20 个文件,而不是使用 ls。
使用以下命令获取 linux 中文件的大小。
du -h <<FileName>>
或者
du -h <<FilePath>>
xargs
获取前一个命令的每一行输出,并基本上在其参数末尾打耳光,因此您的查找打印出类似
的内容
123 ./somefile.txt
xargs
变成
ls -lS 123 ./somefile.txt
除非您在该目录中确实有一个名为 123
的文件,否则您会收到 "cannot access" 错误:
marc@panic:~$ touch foo
marc@panic:~$ ls -lS file_that_does_not_exist foo
ls: cannot access file_that_does_not_exist: No such file or directory
-rw-rw-r-- 1 marc marc 0 Feb 3 14:26 foo
find . -type f |xargs ls -lS |head -20 | awk '{print , }'
由于 ls
的输出是柱状的,只需打印正确的列即可。
在问题中,您声明:
My goal is to print the biggest 20 files in the directory, not using ls.
这意味着可接受的解决方案不应使用 ls
。
另一个问题是xargs
的使用。像 find . -type f | xargs ls
这样的结构不适用于包含白色 space 的子目录或文件名,因为它会将字符串从 find
中拆分出来,然后再提供给 ls
。您可以保护该字符串或使用空终止字符串解决此问题,例如 find . -type f -print0 | xargs -0 ls
。一般情况下,使用xargs
就有security considerations。与其验证你的 xargs
构造是否安全,不如完全避免使用它(尤其是在你不需要它的时候)。
尝试在没有 ls
和没有 xargs
的情况下打印 20 个最大的文件:
find . -type f -printf '%s %p\n' | sort -rn | head -20
没有ls
参与的回答:
find . -type f -printf '%k %p\n' |sort -n |tail -n 20
这给出了每个文件,列出了大小(以 kB 为单位),space,然后是文件名,按数字排序,然后你得到最后 20 个项目(最大的 20 个)。
您的问题出在管道 ls
。
如果你有一个真正 大目录结构,sort
会倒下。您必须使用仅存储最大的 20 项的自定义代码。
所以我有这个有效的命令行。
find . -type f |xargs ls -lS |head -20
问题是我只想输出文件大小和名称。我试过了:
find . -type f -printf '%s %p\n' |xargs ls -lS |head -20
但这给了我一堆 'cannot access [inode], no such file or directory' 错误。
我的目标是打印目录中最大的 20 个文件,而不是使用 ls。
使用以下命令获取 linux 中文件的大小。
du -h <<FileName>>
或者
du -h <<FilePath>>
xargs
获取前一个命令的每一行输出,并基本上在其参数末尾打耳光,因此您的查找打印出类似
123 ./somefile.txt
xargs
变成
ls -lS 123 ./somefile.txt
除非您在该目录中确实有一个名为 123
的文件,否则您会收到 "cannot access" 错误:
marc@panic:~$ touch foo
marc@panic:~$ ls -lS file_that_does_not_exist foo
ls: cannot access file_that_does_not_exist: No such file or directory
-rw-rw-r-- 1 marc marc 0 Feb 3 14:26 foo
find . -type f |xargs ls -lS |head -20 | awk '{print , }'
由于 ls
的输出是柱状的,只需打印正确的列即可。
在问题中,您声明:
My goal is to print the biggest 20 files in the directory, not using ls.
这意味着可接受的解决方案不应使用 ls
。
另一个问题是xargs
的使用。像 find . -type f | xargs ls
这样的结构不适用于包含白色 space 的子目录或文件名,因为它会将字符串从 find
中拆分出来,然后再提供给 ls
。您可以保护该字符串或使用空终止字符串解决此问题,例如 find . -type f -print0 | xargs -0 ls
。一般情况下,使用xargs
就有security considerations。与其验证你的 xargs
构造是否安全,不如完全避免使用它(尤其是在你不需要它的时候)。
尝试在没有 ls
和没有 xargs
的情况下打印 20 个最大的文件:
find . -type f -printf '%s %p\n' | sort -rn | head -20
没有ls
参与的回答:
find . -type f -printf '%k %p\n' |sort -n |tail -n 20
这给出了每个文件,列出了大小(以 kB 为单位),space,然后是文件名,按数字排序,然后你得到最后 20 个项目(最大的 20 个)。
您的问题出在管道 ls
。
如果你有一个真正 大目录结构,sort
会倒下。您必须使用仅存储最大的 20 项的自定义代码。