如何在 macOS 上 rm 名称中包含引号和问号的目录

How to rm directory which name has quotation and question marks on macOS

我有两个名字很奇怪的目录如下:

"?????+ "BizComponent               
"?+ "BizComponent

现在我尝试删除它们但失败了。当我输入 rm -r ' 然后输入 tab 它给我:

"^J^I^I^I^I+ "BizComponent/BizComponent/        
"^J+ "BizComponent/


然后,当我键入 rm -r "^J^I^I^I^I+ "BizComponent/BizComponent/ 时,它会显示 No such file or directory

您的目录名称中似乎有一些特殊字符。您可以使用带有 glob 的循环:

for dir in *BizComponent; do
  rm -r -- "$dir"
done

由于 shell 扩展,您需要转义特殊字符 ? + " ^space。因此,要引用您的文件,您需要 remove/reference 他们喜欢这样:

rm -rf \"\?\?\?\?\?+\ \"BizComponent/

rm -rf \"\?\+\ \"BizComponent

rm -rf \"\^J\^I\^I\^I\^I+\ \"BizComponent/BizComponent/

等等。

你为什么不试试rm -rf "?????+ BizComponent" | echo $?

问题是你的文件名包含一个特殊字符,但这不一定是你看到的字符。示例(取自 here):

$ touch zzz yyy $'zzz\nyyy'
$ ls
yyy  zzz  zzz?yyy

如您所见,创建了一个包含新行的文件名,但 ls 将其打印为 ?。那么我们如何删除它呢?

方法一: ls 可用的选项是 --quoting-style=shell-escape,这允许您查看如何键入要删除的文件名(适用于文件和目录):

$ ls --quoting-style=shell-escape
yyy   zzz  'zzz'$'\n''yyy'
$ rm 'zzz'$'\n''yyy'
$ ls
yyy   zzz

方法 2: 第二种方法是使用 inode 编号 find (适用于文件和目录):

$ touch zzz yyy $'zzz\nyyy'
$ ls -li
total 2
3886009 -rw-r--r-- 1 user group 0 Jul 23 12:56 yyy
3886008 -rw-r--r-- 1 user group 0 Jul 23 12:56 zzz
 662083 -rw-r--r-- 1 user group 0 Jul 23 12:56 zzz?yyy
$ find . -inum 662083 -delete      
$ ls -li
total 1
3886009 -rw-r--r-- 1 user group 0 Jul 23 12:56 yyy
3886008 -rw-r--r-- 1 user group 0 Jul 23 12:56 zzz