Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

437
Views
How to find whether any file of a directory contains a specific string using bash script?

I need to check if the string M1039C28 is inside any file of the directory /var/opt.
It should echo true if the string is found or echo String not found if the string is not found.

Sample:

cd /var/opt/;
if [ find ./ -type f -exec grep -Hni "M1039C28" {} ';']
then
    echo "String found"
else
    INFO "String not found"
fi
over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Consider using grep with options -q (suppress any output) and -r (recursive search in a directory):

grep -qr "search-query" /path/to/dir && echo "FOUND" || echo "NOT FOUND"

grep will exit with code 1 if it could not find the string in any files. For more information, see the man page

over 4 years ago · Santiago Trujillo Report

0

Why don't you base your script on this command:

grep -l "M1039C28" * | wc -l

If the result is 0, then the entry is not found.
If the result is 1 or more, the entry is found.

over 4 years ago · Santiago Trujillo Report

0

If you have a large directory and want to search recursively, try using the silver searcher if not already installed, you can with on Debian sudo apt install silversearcher-ag or brew install the_silver_searcher on MacOS. Use it like this.

ag "M1039C28" path/to/search && echo "FOUND" || echo "NOT FOUND"

note path argument is optional, by default it searches current path recursively.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!