gpt4 book ai didi

linux - Bash - : ls | grep 的替代品

转载 作者:太空狗 更新时间:2023-10-29 11:35:34 25 4
gpt4 key购买 nike

我在脚本中使用以下管道作为变量:

match=$( ls | grep -i "$search")

然后在 if 语句中使用:

if [ "$match" ]; then
echo "matches found"
else
echo "no matches found"
fi

如果我不想使用查找,有什么替代方案? ShellCheck建议:

ls /directory/target_file_pattern

但我没有得到相同结果的正确语法。当 if 语句 无法工作时,我也希望没有输出

最佳答案

如果你只是想判断是否存在与 bash 的任何匹配项,你可以像这样使用内置的 compgen:

if compgen -G 'glob_pattern_like_your_grep' >/dev/null; then
echo "matches found"
else
echo "no matches found"
fi

如果你想对匹配的文件进行操作,find 通常是适合这项工作的工具:

find . -name 'glob_pattern_like_your_grep' -exec 'your command to operate on each file that matches'

关键是你必须使用 glob patterns ,而不是正则表达式类型模式。

如果您的find 支持它,您也许可以匹配正则表达式,例如

find . -regex 'pattern'

并在 if-exec

中使用它

关于linux - Bash - : ls | grep 的替代品,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45405034/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com