Comparing files in a directory against an array of files

I hope I can explain this correctly. I am using Bash-4.2 for my shell.

I have a group of file names held in an array. I want to compare the names in this array against the names of files currently present in a directory. If the file does not exist in the directory, that is not a problem. However, if any file exists in the directory that is not also listed in the array, the file in the directory should be deleted. I just cannot find a relatively simple way to do this.

so, where are you stuck with your code? are you getting any error?

--ahamed

I have tried literally dozens of ways to do it, and while I have certainly found a few that work, they are all to inflated in my opinion. I am just trying to find an eloquent method if possible.

This would be a lot easier in a language with associative arrays; you could check if the file was in the set in one operation instead of a loop.

KEEP=( file1 file2 file3 )

for FILE in *
do
        DEL=1
        for X in "${KEEP[@]}"
        do
                [ "$X" = "$FILE" ] && DEL=0
        done

        [ "$DEL" -eq 1 ] && echo rm "$FILE"
done

Remove the echo once you've tested and are sure this does what you want.

1 Like

Bash 4x supports associative arrays I believe; however, I have no experience with them. I just use the regular arrays. If you could give me an example of how this would work with an associative array, I might learn something.

Thanks!

With assosciative arrays in bash4 you could try something like this:

declare -A KEEP=( [file1]=1 [file2]=1 [file3]=1 )
for file in *
do 
  if [[ ! ${KEEP[$file]} ]]; then
    echo rm "$file"
  fi
done

Remove the echo once you have tested it and it does what you want..