Bash - 替代:ls | grep

Bash - alternative for: ls | grep

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

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 语句 没有匹配项时,我也希望 no output 起作用。

如果你只想判断是否存在与 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

中使用它

使用find:

match="$(find . -path "*${search}*" -printf "." | wc -c)"

$match 将包含匹配数。你可以这样检查:

if [ "${match}" -gt 0 ] ; then
    echo "${match} files found"
else
    echo "No files found"
fi