1

I'm trying to build a function that:

  • Gets arguments and assigns them to an array.
  • Removes all the elements that match the Exclude file.

Exclude file is a text file that contains a list of strings to exclude separated by lines.

For example:

The Exclude file is: list.txt. It contains:

value1

value2

Let's assume we call the function with these arguments:

Function value1 value2 value3

The desired output would be:

value3

So far I tried to iterate through the list.txt and overwrite the array with array minus the String from the file. But it seems that it doesn't overwrite the array and instead it appends the values.

The output I get right now is:

value3 value2 value3

My code is:

function Function {
    argsArr=( "$@" )
    while read p; do
        argsArr="${argsArr[@]//$p*/}"
    done <list.txt
    echo "${argsArr[@]}"
}
2
  • 1
    Your code is correct only change is replace ""(double quotes) in line 4 with braces(). It should work i have tested and found it working. Remove extra slash before $p in 4th line. Commented Mar 16, 2016 at 10:17
  • @Koushik Thank you too, you can post this as an answer and I'll upvote it. Commented Mar 16, 2016 at 10:22

2 Answers 2

2

A simple grep check would suffice:

$ cat list.txt 
value1
value2
$ function Function
> {
> for i in "$@"
> do
> fgrep -q "$i" list.txt || echo "$i"
> done
> }
$ Function value1 value2 value3
value3
$

We just iterate through the parameters passed to function and grep for that parameter in list.txt(Exclude file), if exit code is non-0 i.e not present we then just print it out.

If you want the result in array, declare it at start of function using array=(), just append the parameter to an array like this: fgrep -q "$i" list.txt || array+=("$i") and at the end of function just do echo ${array[@]}

Edit 1: just using an array

$ function Function
> {
> declare -a array=()
> for i in "$@"
> do
> fgrep -q "$i" list.txt || array+=("$i")
> done
> echo "${array[@]}"
> }
$ Function value1 value2 value3
value3
$
Sign up to request clarification or add additional context in comments.

Comments

1

Check out line 4:

function Function {

    argsArr=( "$@" )
    while read p; do
        argsArr=(${argsArr[@]/$p*/})
    done <list.txt
    echo "${argsArr[@]}"
}

Comments

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.