检查带空格返回的文件的磁盘使用情况

Chr*_*ris 7 linux bash sed command-line

我想输出由find.

我的一个文件的名称中有空格,这导致du为其返回“没有这样的文件或目录”消息。

chris@chris-x1c6:/media/E/2Videos$ du -ch $(find . -maxdepth 1 -iname "*syed*")
du: cannot access './The': No such file or directory
du: cannot access 'Case': No such file or directory
du: cannot access 'Against': No such file or directory
du: cannot access 'Adnan': No such file or directory
du: cannot access 'Syed': No such file or directory
du: cannot access 'S01E01': No such file or directory
du: cannot access '1080p.WEB.H264-AMRAP.mkv': No such file or directory
4.0G    ./The.Case.Against.Adnan.Syed.S01E02.In.Between.the.Truth.1080p.AMZN.WEB-DL.DDP5.1.H.264-NTb.mkv
4.0G    ./The.Case.Against.Adnan.Syed.S01E03.1080p.WEB.H264-AMRAP.mkv
3.5G    ./The.Case.Against.Adnan.Syed.S01E04.Time.is.the.Killer.1080p.AMZN.WEB-DL.DDP5.1.H.264-NTb.mkv
12G total
Run Code Online (Sandbox Code Playgroud)

我已经尝试通过管道处理空格sed并将文件名括在引号中或在空格中添加转义字符,这两种方法都不允许du识别带有空格的文件名。

这有点令人困惑,因为它有效:

chris@chris-x1c6:/media/E/2Videos$ du -ch ./The\ Case\ Against\ Adnan\ Syed\ S01E01\ 1080p.WEB.H264-AMRAP.mkv 
4.1G    ./The Case Against Adnan Syed S01E01 1080p.WEB.H264-AMRAP.mkv
4.1G    total
Run Code Online (Sandbox Code Playgroud)

但这不会:

chris@chris-x1c6:/media/E/2Videos$ du -ch $(find . -maxdepth 1 -iname "*syed*" | sed 's/ /\\ /g')
du: cannot access './The\': No such file or directory
du: cannot access 'Case\': No such file or directory
du: cannot access 'Against\': No such file or directory
du: cannot access 'Adnan\': No such file or directory
du: cannot access 'Syed\': No such file or directory
du: cannot access 'S01E01\': No such file or directory
du: cannot access '1080p.WEB.H264-AMRAP.mkv': No such file or directory
4.0G    ./The.Case.Against.Adnan.Syed.S01E02.In.Between.the.Truth.1080p.AMZN.WEB-DL.DDP5.1.H.264-NTb.mkv
4.0G    ./The.Case.Against.Adnan.Syed.S01E03.1080p.WEB.H264-AMRAP.mkv
3.5G    ./The.Case.Against.Adnan.Syed.S01E04.Time.is.the.Killer.1080p.AMZN.WEB-DL.DDP5.1.H.264-NTb.mkv
12G total
Run Code Online (Sandbox Code Playgroud)

有没有更好的方法来处理这个问题?

fd0*_*fd0 22

如果我们让 find 处理文件名怎么办?

find . -maxdepth 1 -iname '*syed*' -exec du -ch {} +
Run Code Online (Sandbox Code Playgroud)


Del*_*tik 12

这个怎么样?:

找 。-maxdepth 1 -iname '*syed*' -print0 | xargs -0 du -ch

选项说明:

  • find – 您用来查找文件的工具
    • -print0 – 用空字符分割每个结果,这是一个不能出现在文件名中的字符
  • xargs – 将参数组装到从标准输入 (stdin) 管道传输的命令中
    • -0 – 接收由空字符分割的每个参数
    • du -ch – 要将文件参数传递给的命令

至于为什么您提出sed的转义方式不起作用,\您尝试添加的字符是在 shell 参数分隔符 (" ") 转义已经发生之后放入的。每个由空格分隔的单词已经是一个参数。

我的解决方案 withxargs确保每个参数都是来自 的路径find,无论空格如何。