1

I am having a directory in which it contains 20 sub-directories and all sub-directories names end with "_b". In each sub-directory same file name "error.txt" is there. I need to loop-in to all the sub-directories and grep for a word called "ECHO" in the "sub-directory/error.txt" file and if the word is present I need to execute statement one, if the word "ECHO" is not present in file "sub-directory/error.txt" I need to execute statement two. I tried like this:

#!/bin/bash
File="./error.txt"
for d in *_b;
do
if grep -q "ECHO" "$File"; then
echo "$d:";
    Statement 1 
echo "------------------";
else 
echo "$d:";
    Statement 2 
echo "------------------";
fi
done

But I am not getting the desired output , I am getting output as :

grep: ./error.txt: No such file or directory
2
  • find *_b -maxdepth 1 -type f -iname error.txt -print0 | while read -r -d '' file; do if grep -qi ECHO "$file"; then ... else ... fi; done is the better choice loop over non-trivial file names (example) and maybe case-insensitive search (i) give more results Commented Aug 23, 2020 at 11:22
  • Not the problem you're asking about but don't duplicate code - move the echo "$d:"; to before your if-else and the echo "------------------"; to after it. You don't need the ;s btw. Commented Aug 23, 2020 at 13:38

1 Answer 1

1

I just adjusting the path should work

#!/bin/bash
File="error.txt"
for d in *_b;
do
if grep -q "ECHO" $d/"$File"; then
echo "$d:";
    Statement 1
echo "------------------";
else
echo "$d:";
    Statement 2
echo "------------------";
fi
done
Sign up to request clarification or add additional context in comments.

2 Comments

I am still seeing the same error as: grep: error.txt: No such file or directory. Here error.txt is a common file name in all 20 sub-directories, I need to loop in to all 20 sub-directories and grep for the word "ECHO" in "error.txt" file.
sure it isn't grep: *_b/error.txt: No such file or directory i can barely see a reason how $d can be empty (nevertheless path should quoted with double quotes)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.