Interview questions: bash script

Question:

Need to write the bash script which prints the list of filenames from a directory tree, each of them:

  • has extension "*.c"
  • contains a string "HelloWorld"

Solution:

One-line

# Basic one
$ fgrep --include="*.c" -lre "HelloWorld"
# With word-boundary
$ grep --include="*.c" -lrPe '\bHelloWorld\b'
# Grep without recursive mode
$ find . -type f -name '*.c' -print0 | xargs -0 grep -le "HelloWorld"
# Without xargs
$ find . -type f -name '*.c' -exec grep -q "HelloWorld" {} \; -print
# I prefer to use rg (RipGrep) when it's available.
$ rg -l -g "*.c" "HelloWorld"

Multiline

#!/bin/bash
for i in $(find . -type f -name '*.c')
do
   if cat "$i" | grep -q "$1"
   then
      echo "Found $i"
   fi
done

Comments

comments powered by Disqus