You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Cygwin的find命令输出含特殊字符的文件大小与路径

适配任意字符文件名的文件大小与路径导出方案

问题场景

需要导出指定目录下所有文件的「文件大小(字节)|文件完整路径」格式内容,示例输出:

100|path/to/directory/a/file1.txt
200|path/to/directory/b/file2.txt
321|path/to/directory/c/d/file3.txt

原使用命令:

find path/to/directory -maxdepth 3 -type f -printf "%s|%p\n" > path/to/output.txt

但遇到含空格的目录时触发错误:find: 'path/to/directory/my directory 1': No such file or directory;在Cygwin或MSYS2环境下,含多字节字符的长文件名(未超Windows 255字符限制)也会出现类似报错。

适配方案

1. 处理含空格的目录(通用POSIX环境)

只需将目标目录路径用双引号包裹,避免空格被shell解析为多个参数:

find "path/to/directory" -maxdepth 3 -type f -printf "%s|%p\n" > path/to/output.txt

如果目录路径通过变量传递,同样确保变量被双引号包裹:

target_dir="path/to/directory with spaces"
find "$target_dir" -maxdepth 3 -type f -printf "%s|%p\n" > output.txt

2. Cygwin/MSYS2环境适配多字节字符文件名

由于Cygwin/MSYS2与Windows文件系统的兼容性问题,可通过以下两种方式规避:

  • 方法一:使用PowerShell替代
    PowerShell对Windows原生文件名支持更完善,执行命令:
    Get-ChildItem -Path "path/to/directory" -MaxDepth 3 -File | ForEach-Object { "$($_.Length)|$($_.FullName)" } | Out-File -FilePath "path/to/output.txt" -Encoding UTF8
    
  • 方法二:调整Cygwin/MSYS2路径转换行为
    设置环境变量禁用自动路径转换,避免多字节字符被错误解析:
    export MSYS_NO_PATHCONV=1
    find "path/to/directory" -maxdepth 3 -type f -printf "%s|%p\n" > path/to/output.txt
    
    若需永久生效,可将export MSYS_NO_PATHCONV=1添加到~/.bashrc或~/.zshrc配置文件中。

内容的提问来源于stack exchange,提问作者lyrically wicked

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 15:27:50