如何使用 POSIX 在 bash 中找到异常字符 '?

How to find the unusual character ' using POSIX in bash?

这里有一些名字:

El Peulo'Pasa, Van O'Driscoll, Mike_Willam

如何通过命令 find 在 bash 中使用 POSIX 来过滤包含 ' 的名称?

如果我使用下面的命令,

find . -maxdepth 1 -mindepth 1 -type d -regex '^.*[']*$' -print

Bash 遇到问题,因为语法 ' 会自动将输入转换为字符串

您根本不需要 -regex (which is a non-POSIX action); -name 绰绰有余。 (-mindepth-maxdepth 也是 POSIX 标准中不存在的扩展。

要生成 ' 文字,请将其放在双引号内,或放在不带引号的上下文中并在其前面加上反斜杠:

find . -maxdepth 1 -mindepth 1 -type d -name "*'*" -print

...或 100% 相同但更难阅读的命令行...

find . -maxdepth 1 -mindepth 1 -type d -name '*'\''*' -print

如果您只是搜索当前目录(而不是其子目录),您甚至不需要 find,只需一个通配符(“glob”)表达式:

ls *\'*

(注意 ' 必须转义或双引号,但星号不能。)

如果要对这些文件进行操作,可以直接使用通配符表达式:

dosomethingwith *\'*
# or
for file in *\'*; do
    dosomethingwith "$file"
done

...或者如果您使用 bash,将文件名存储在一个数组中,然后使用它。这涉及到正确引用,以避免文件名中的其他奇怪字符(例如空格)出现问题:

filelist=( *\'* )
dosomethingwith "${filelist[@]}"
# or
for file in "${filelist[@]}"; do
    dosomethingwith "$file"
done

这里要注意的是,数组 不是 POSIX shell 标准的一部分;它们在某些 shells(bash、ksh、zsh 等)中工作,但在其他(例如 dash)中不工作。如果你想使用数组,一定要使用正确的 shebang 来获得你想要的 shell(并且不要用 运行 带有 sh scriptname 的脚本覆盖它)。