This is an assignment question, so I'm not directly looking for an answer or the script. So in one of my questions, I'm asked that I should delete the files containing any of the passed command line arguments. Here is the script snippet for that


#some more stuff here

for args in "$@"; do
    if  [ $#  != 0 ]; then
        grep -l $args * | while read theFile; 
            if [ -f "$theFile" ] ; then
                rm "$theFile"
                echo "$theFile is deleted with $args match"
                echo "$theFile not deleted"
                exit 2
        done #end of while loop
        echo "No match found with $args"
        exit 1
echo "DONE"
exit 0 

Now, I'd like to know how I would write the script so that it would delete the files that have ALL the arguments? I understand that I need to check if each file has the arguments passed with either a for loop, but I'm not sure how I'd be writing it. Any inputs will be appreciated.

I'm using cloud9 to practice, if that info is needed.


You're now looping over the keywords (for arg in..), and then, for each keyword, checking which files contain that keyword (grep -l $arg *).

To check for files that have all keywords you could invert that, and loop over all files (for f in *), and then loop over the keywords (for arg in "$@"), checking if the file contains them (grep -qe "$arg" "$f") only removing if all of them match.

That's a bit of a brute force, as you'd execute grep n*m times, for n files and m keywords. The alternative would be to run grep -l for the first keyword, then grep -l for the second keyword, giving grep the list of files returned by the last grep, etc. You'd probably want to save the list of files in an array in every step.

As a side note, this doesn't make any sense:

for args in "$@"; do
    if  [ $#  != 0 ];

You're checking the number arguments inside a loop that runs once for each argument. $# is zero exactly when there are no arguments, but then "$@" doesn't contain anything either, and the loop will not run.


grep -l $args * | while read theFile; 

You should probably quote $args, and you may also want to take a look at BashFAQ 001 for info about using while read ...

In short, you probably want

grep -l "$args" * | while IFS= read -r theFile; do

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.