我目前正在尝试使用 bash 遍历特定目录中的所有文件。如果文件匹配以下正则表达式,则输出文件名。如果不是,则输出“not”,然后输出文件名。正则表达式应该过滤掉任何带有“。”的文件。在其中。
for f in * ; do
if [[ $f =~ "^[^\.]+$" ]]; then
echo "$f"
else
echo "not $f"
fi
done
它正确地遍历了所有文件,但由于一个困扰我很长一段时间的原因,我无法让它只排除带有“.”的文件。在他们中。例如,在包含以下文件的目录中:
bashrc
gitconfig
install.sh
README.md
vimrc
脚本的输出是这样的:
not bashrc
not gitconfig
not install.sh
not README.md
not vimrc
我验证了正则表达式 here .有什么想法吗?
最佳答案
不要引用表达式的右侧。
if [[ $f =~ ^[^.]+$ ]]; then
引号使字符串成为文字子字符串,而不是正则表达式。 为了更好地跨 bash 版本的可移植性,将您的正则表达式放在一个变量中(单引号,这将使反斜杠文字):
re='^[.]+$'
if [[ $f =~ $re ]]; then
也就是说,您也可以使用 extglob 执行此操作:
shopt -s extglob # enable extended globs
for f in +([!.]); do
printf 'Matched %q\n' "$f"
done
...或使用通用模式匹配:
for f in *; do
if [[ $f = *.* ]]; then
printf '%q contains a dot\n' "$f"
else
printf '%q does not contain a dot\n' "$f"
fi
done
关于regex - native bash 正则表达式 [[ $f =~ "^[^\.]+$"]] 从不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32317587/