繁体   English   中英

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

如果我不想使用find,会有什么替代方法? 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模式 ,而不是regex类型模式。

如果您find支持的话,你也许能匹配正则表达式像

find . -regex 'pattern'

并在if-exec使用它

使用find

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

$match将包含$match数。 您可以像这样检查它:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM