[英]Bash - alternative for: ls | grep
I use the following pipe as variable in a script: 我在脚本中使用以下管道作为变量:
match=$( ls | grep -i "$search")
this is then used in an if statement : 然后在if语句中使用它 :
if [ "$match" ]; then
echo "matches found"
else
echo "no matches found"
fi
what would be an alternative if I did not want to use find? 如果我不想使用find,会有什么替代方法? ShellCheck recommends:
ShellCheck建议:
ls /directory/target_file_pattern
ls / directory / target_file_pattern
but I do not get the syntax right to get the same result. 但是我没有正确的语法来获得相同的结果。 also I want no output when there are no matches for the if statement to work.
当if语句不匹配时,我也不想输出 。
If you just want to tell if there exist any matches with bash
you could use the builtin compgen
like so: 如果您只是想知道
bash
是否存在任何匹配项,则可以使用内置的compgen
如下所示:
if compgen -G 'glob_pattern_like_your_grep' >/dev/null; then
echo "matches found"
else
echo "no matches found"
fi
if you want to operate on the files that are matched, find
is usually the right tool for the job: 如果要对匹配的文件进行操作,
find
通常是适合该工作的工具:
find . -name 'glob_pattern_like_your_grep' -exec 'your command to operate on each file that matches'
the key though is that you have to use glob patterns , not regex type patterns. 但是关键是您必须使用glob模式 ,而不是regex类型模式。
If your find
supports it, you might be able to match a regex like 如果您
find
支持的话,你也许能匹配正则表达式像
find . -regex 'pattern'
and use that in either the if
or with -exec
并在
if
或-exec
使用它
Use find
: 使用
find
:
match="$(find . -path "*${search}*" -printf "." | wc -c)"
$match
will contain the number of matches. $match
将包含$match
数。 You can check it like this: 您可以像这样检查它:
if [ "${match}" -gt 0 ] ; then
echo "${match} files found"
else
echo "No files found"
fi
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.