简体   繁体   中英

Script Linux Bash, print grep output based on number of words in line

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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