简体   繁体   English

如何在bash中使用grep匹配文件夹名称并在if条件下使用它?

[英]How to match a folder name and use it in an if condition using grep in bash?

for d in */ ; do
    cd $d
    NUM = $(echo ${PWD##*/} | grep -q "*abc*");
    if [[ "$NUM" -ne "0" ]]; then
        pwd
    fi
    cd ..
done

Here I'm trying to match a folder name to some substring 'abc' in the name of the folder and check if the output of the grep is not 0. But it gives me an error which reads that NUM: command not found 在这里,我尝试将文件夹名称与文件夹名称中的某些子字符串'abc'匹配,并检查grep的输出是否不为0。但这给我一个错误,提示读取NUM: command not found


An error was addressed in comments. 评论中已解决错误。 NUM = $(echo ${PWD##*/} | grep -q "*abc*"); should be NUM=$(echo ${PWD##*/} | grep -q "*abc*"); 应该为NUM=$(echo ${PWD##*/} | grep -q "*abc*"); .


To clarify, the core problem would be to be able to match current directory name to a pattern. 为了澄清,核心问题将是能够将当前目录名与模式匹配。

You can probably simply the code to just 您可能只需将代码

if grep -q "*abc*" <<< "${PWD##*/}" 2>/dev/null; then
   echo "$PWD"
   # Your rest of the code goes here
fi

You can use the exit code of the grep directly in a if-conditional without using a temporary variable here ( $NUM here). 您可以在if条件中直接使用grep的退出代码,而无需在此处使用临时变量(此处$NUM )。 The condition will pass if grep was able to find a match. 如果grep能够找到匹配项,则条件将通过。 The here-string <<< , will pass the input to grep similar to echo with a pipeline. 这里的字符串<<< ,会将输入传递给grep类似于使用管道的echo The part 2>/dev/null is to just suppress any errors ( stderr - file descriptor 2 ) if grep throws! 2>/dev/null grep抛出时仅抑制任何错误( stderr - file descriptor 2 )!


As an additional requirement asked by OP, to negate the conditional check just do 作为OP的附加要求,否定条件检查就可以了

if ! grep -q "*abc*" <<< "${PWD##*/}" 2>/dev/null; then

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

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