关于bash:find命令无法在具有空格和特殊字符的目录中工作

find command not working in directories with space and special character

本问题已经有最佳答案,请猛点这里访问。

我正在尝试使用"find"命令来查找特定的文件名。但是,它包含空格和"()"符号。我试图跟踪

1
2
3
cspath="/cygdrive/e/dir/dir1/OneDrive - The Asia Group/TAG (1)/Works in Progress/Brian/Jaycees/Firecracker 4 Mile Road Race - 2015 Shirt_files"

/usr/bin/find $cspath -print0

但它显示的错误如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
find: ‘/cygdrive/e/dir/dir1/OneDrive’: No such file or directory
find: ‘-’: No such file or directory
find: ‘The’: No such file or directory
find: ‘Asia’: No such file or directory
find: ‘Group/TAG’: No such file or directory
find: ‘(1)/Works’: No such file or directory
find: ‘in’: No such file or directory
find: ‘Progress/Brian/Jaycees/Firecracker’: No such file or directory
find: ‘4’: No such file or directory
find: ‘Mile’: No such file or directory
find: ‘Road’: No such file or directory
find: ‘Race’: No such file or directory
find: ‘-’: No such file or directory
find: ‘2015’: No such file or directory
find: ‘Shirt_files’: No such file or directory*

我还尝试了以下方法:

1
find"{$cspath}" -print0

但错误再次出现(这次在每个空格中打印)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
find: ‘{/cygdrive/e/dir/dir1/OneDrive
-
The
Asia
Group/TAG
(1)/Works
in
Progress/Brian/Jaycees/Firecracker
4
Mile
Road
Race
-
2015
Shirt_files}’: No such file or directory

请建议


你很接近,变量在bash中被写为$variable${variable}

现在,您需要引用以便bash不进行字段拆分和路径名扩展,这对您很重要,因为路径中有空格。做:

1
find"${cspath}" -print0

1
find"$cspath" -print0

第一次不带引号的尝试失败了,因为文件路径中有空间,而bash正在对空白区域执行字段拆分,只需引用就可以了。


问题是,如果测试有空白,那么cygpath -u $test会在新行上生成多条路径,修复方法是cygpath -u"$test"

这对我很有用-Cygwin工具通常可以处理路径中的空白-仍然需要注意-我的规则是,如果我能帮助的话,不要在任何路径或文件名中使用空白。

1
2
3
4
5
6
7
8
9
10
11
12
$ pth="/cygdrive/c/dir with spaces (and parens)"
$ find"$pth"
/cygdrive/c/dir with spaces (and parens)
/cygdrive/c/dir with spaces (and parens)/file0 with spaces (and parens)
/cygdrive/c/dir with spaces (and parens)/file1 with spaces (and parens)

# cygwin and find versions
$ uname -r
2.5.1(0.297/5/3)
$ find --version
find (GNU findutils) 4.6.0
Packaged by Cygwin (4.6.0-1)