Home > Software engineering >  Using multiple arguments to find and grep
Using multiple arguments to find and grep

Time:04-14

I am trying to make a script so that I can give command with variable number of arguments myfind one two three and it finds all files in the folder, then applies grep -i one then grep -i two, and grep -i three and so on.

I tried following code:

#! /bin/bash
FULLARG="find . | "
for arg in "$@"
do 
    FULLARG=$FULLARG" grep -i "$arg" | "
done
echo $FULLARG
$FULLARG

However, though the command is created but it is not working and giving following error:

$ ./myfind one  two three
find . | grep -i one | grep -i two | grep -i three |
find: unknown predicate `-i'

Where is the problem and how can it be solved?

CodePudding user response:

You could store the result of find . and keep filtering that out till you have command line arguments:

#!/bin/bash

result="$(find .)"
for arg in "$@"
do
    result=$(echo "$result" | grep -i "${arg}")
done

echo "$result"
  • Related