linux - 如何删除这样命名的文件?

标签 linux shell

<分区>

我的主文件夹中有两个名为“'?”的文件和 ”'?;?” (没有双引号)。我怎样才能删除它们?我试过使用转义,但它不起作用。

最佳答案

使用单引号或双引号避免通配符扩展。 ? 是一个通配符,指示 shell 与任何一个字符匹配。通过将它放在引号中,您告诉 shell 不要执行通配符扩展。

rm '?' '?;?'
rm "?" "?;?"

这将删除名为“?”的两个文件和“?;?”

您还可以使用反斜杠来引用对 shell 具有特殊含义的单个字符,这样您就可以这样做

rm \? \?\;\?

请注意,您必须引用 '?'为了防止路径名扩展,你必须引用 ';'所以 shell 不会将其解释为分隔命令。

如果您省略引号,则 shell 会以不同的方式解析它。这是我进行的一个实验。

$ for i in {1..4}; do for j in {a..c}; do touch "$i;$j" $j '?' '?;?';done;done
$ ls
1;a  1;b  1;c  2;a  2;b  2;c  3;a  3;b  3;c  4;a  4;b  4;c  ?  ?;?  a  b  c
$ rm ? ?;?
rm: cannot remove `?': No such file or directory
rm: cannot remove `a': No such file or directory
rm: cannot remove `b': No such file or directory
rm: cannot remove `c': No such file or directory
bash: ?: command not found
$ rm `echo "?" "?;?"`
rm: cannot remove `?': No such file or directory
$ 

这里发生的是 shell 做了路径名扩展,所以

rm ? ?;?

成为

rm ? a b c ? a b c;? a b c

rm 命令删除了文件 a b c ?然后提示找不到以下文件(它们已被删除)。分号分隔命令,因此它会尝试调用“?”命令传递参数“a”“b”“c”......但没有“?”命令 - 名为“?”的文件刚刚被删除,而且它无论如何都不可执行 - 所以 shell 提示“?”找不到命令。

如果你想删除所有匹配“?”的文件和 ”?;?”你需要欺骗 shell 来扩展它们,我就是这样做的

rm `echo "?" "?;?"`

这由 shell 分两步展开,首先它运行 echo "?""?;?" 结果是两个字符串,"?"和“?;?”,然后它使用这些字符串进行路径名扩展以生成 rm 的参数,这导致

rm  ? 1;a  1;b  1;c  2;a  2;b  2;c  3;a  3;b  3;c  4;a  4;b  4;c ?;?

请注意“?”的通配符扩展这次没有产生任何匹配的文件(它们之前已经被删除),所以 shell 通过 '?'作为 rm 的参数,它成功地删除了作为参数传递的所有文件,除了 '?'所以它对此有所提示。

还有一个实验

$ for i in {1..4}; do for j in {a..c}; do touch "$i;$j" $j '?' '?;?';done;done
$ ls
1;a  1;b  1;c  2;a  2;b  2;c  3;a  3;b  3;c  4;a  4;b  4;c  ?  ?;?  a  b  c
$ rm "?" "?;?"
$ ls
1;a  1;b  1;c  2;a  2;b  2;c  3;a  3;b  3;c  4;a  4;b  4;c  a  b  c
$ rm `echo "?" "?;?"`
$ ls
$ 

有关更多信息,请参阅有关 globbing 的手册页

man 7 glob

Wildcard Matching A string is a wildcard pattern if it contains one of the characters '?', '*' or '['. Globbing is the operation that expands a wildcard pattern into the list of pathnames matching the pattern. Matching is defined by:

   A '?' (not between brackets) matches any single character.

   A '*' (not between brackets) matches any string, including the empty string.

关于linux - 如何删除这样命名的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22285519/

相关文章:

bash - 在 grep 中搜索字符串模式以获取滑动窗口

shell - 如何在 shell 脚本上运行 SDKMAN

linux - 如果输出重定向到记录器,Shell 脚本不会退出

linux - 将 yocto 中的默认 rootfs 文件权限更改为 750 而不是 755

linux - chmod : missing operand after a+t

shell - 使用 gnu 并行处理带标题的 CSV 文件

linux - 如何找出文件的 MIME 类型(Content-Type)?

linux - "Couldn' t 在 Windows 上的 Ubuntu bash 上找到引用控制台的文件描述符

linux - 跟踪 Linux 上的上下文切换

linux - nasm gcc 命令错误,子程序作为单独的文件