0

I'm trying to write a scirpt for the bash shell. I'm given 4 parameters:

  1. path of a directory
  2. extension of a file
  3. a word
  4. a number

I have to look for all files and files of subdirectories of the path, for files with the given extension. Then, look in the files for the lines matching the word given, but only if the number of words in the line is bigger or equal to the number provided.
For example:
If localDirectory has: image.png script.sh text.txt.
And text.txt has:

This is a text file
It contains many words
This is an example for a simple text file

Then give the command: ./example.sh localDirectory txt text 7
I should output: This is an example for a simple text file.

For now, my script looks like this:

if [ "$#" -ne 4 ];
then
  echo "Not enough parameters"
  exit 1
fi
find $1 -name "*.$2" -exec grep -wi $3  {} \;

And it works just fine for the first 3 goals, I just don't know how to filter now the result such that the line has a greater or equal number of words as $4.

I could of course create a new file and output there, and then read from it and print only the relevant lines, but I would rather do this without creating new files.

I'm very new to shell scripting.

Any ideas?

0

1 Answer 1

1

Use awk so you can test NF (the number of fields in the line).

Also remember to quote all your variables.

find "$1" -name "*.$2" -exec awk -v word="${3,,}" -v count="$4" 'NF >= count && tolower($0) ~ word' {} +

${3,,} converts $3 to lowercase, and tolower($0) converts the file line to lowercase, so comparing them makes it case-insensitive.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! How about the wi flag added in the grep? I see here is sensitive case
Are you using GNU awk? It's easier to solve then.
See superuser.com/questions/349104/awk-match-whole-word for various ways to match whole words in awk.

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.