Bash 脚本:变量中的文件夹列表并 grep 确切的目录名称
这是我的问题。要获取文件 GC.xml 所在的目录列表:
EXBRANDS=
查找 /var/www/html/ -maxdepth 3 -name "GC.xml" -type f | awk -F '/' '{print $5}';
#echo $EXBRANDS
#dir1 dir2 dir3 (看起来完全像这样)
< code>#read var
例如输入“dir”,
这就是我无法识别我键入的确切模式以将其与目录列表进行比较的地方。
回显 $EXBRANDS | grep "[ $var]\|[$var ]\|[ $var]" 如果 [[ $? -eq 0]]; then ..... else ..... fi;
我认为我的 grep 命令有问题,就好像我将值“dir”传递给 $var 我的 grep 命令实际上找到了目录并返回 $ ?=0
我的愿望是仅当它在 grep 命令中准确找到模式 $var 时才获得 $?=0...
这里最好的 grep (egrep) 选项是什么?还是我的方法完全愚蠢?
Here is my problem. To get a list of directory where the file GC.xml is:
EXBRANDS=
find /var/www/html/ -maxdepth 3 -name "GC.xml" -type f | awk -F '/' '{print $5}';
#echo $EXBRANDS
#dir1 dir2 dir3 (it appears exactly like this)
#read var
Enter "dir" for example
That's where I'm having trouble to identify the exact pattern I typed to compare it against my directory list.
echo $EXBRANDS | grep "[ $var]\|[$var ]\|[ $var]"
if [[ $? -eq 0 ]] ; then ..... else ..... fi;
I think there is a problem with my grep command as if I pass the value "dir" to $var my grep command actually finds the directory and returns $?=0
My wish is to get $?=0 only if it finds exactly the pattern $var in my grep command...
What are the best grep (egrep) options here? Or is my method completely stupid?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的
EXBRANDS
包含许多行,并且您通过 echo 松开了这些行。我会以另一种方式做到这一点:
确保 grep 与
"^$var\$"
构造精确匹配。编辑:您还可以
printf "$EXBRANDS" | grep "^$var\$"
而不是 echo,它可能会解决您的问题。Your
EXBRANDS
contains many lines, and you loose these lines with echo.I would do that the other way:
Be sure that the grep match an exact line with the
"^$var\$"
construct.Edit: you could also
printf "$EXBRANDS" | grep "^$var\$"
instead of echo, it might solve your problem.尝试使用单词边界:
编辑:添加空检查
Try using word boundaries:
EDIT: add null check