Search code examples
bashscriptingfilenamesdelete-file

How to remove files from a directory if their names are not in a text file? Bash script


I am writing a bash script and want it to tell me if the names of the files in a directory appear in a text file and if not, remove them.

Something like this:

counter = 1
numFiles = ls -1 TestDir/ | wc -l 
while [$counter -lt $numFiles]
do
     if [file in TestDir/ not in fileNames.txt]
     then
          rm file
     fi
     ((counter++))
done

So what I need help with is the if statement, which is still pseudo-code.


Solution

  • You can simplify your script logic a lot :

    #/bin/bash
    
    # for loop to iterate over all files in the testdir
    for file in TestDir/*
    do
        # if grep exit code is 1 (file not found in the text document), we delete the file
        [[ ! $(grep -x "$file" fileNames.txt &> /dev/null) ]] && rm "$file"
    done