Search code examples
linuxbashshellgrepwc

I want to check if some given files contain more then 3 words from an input file in a shell script


My first parameter is the file that contains the given words and the rest are the other directories in which I'm searching for files, that contain at least 3 of the words from the 1st parameter

I can successfully print out the number of matching words, but when testing if it's greater then 3 it gives me the error: test: too many arguments

Here's my code:

#!/bin/bash

file=$1
shift 1

for i in $*
do
    for j in `find $i`
    do
        if test -f "$j"
        then
            if test grep -o -w "`cat $file`" $j | wc -w -ge 3
            then
                echo $j
            fi
        fi
    done


done

Solution

  • You first need to execute the grep | wc, and then compare that output with 3. You need to change your if statement for that. Since you are already using the backquotes, you cannot nest them, so you can use the other syntax $(command), which is equivalent to `command`:

    if [ $(grep -o -w "`cat $file`" $j | wc -w) -ge 3 ]
    then
        echo $j
    fi