Sunday, February 27, 2022

[SOLVED] Bash - Removing files using Arrays

Issue

I have one flat directory. I have 2 arrays. Array1 stores the contents of the directory (all .PNG files). Array2 has six files. These six files are the same as the six files within Array1. How do I use Array2 to remove the 6 files in the directory? Two arrays are as follows:

array1= (`ls ${files}*.PNG`)
array2= $(find . ! -name 'PHOTO*')

Tried using a for loop but not sure how to proceed:

for files in $array2;do
    rm -f files $array1

Solution

  1. No space is allowed after the = in an assignment.

  2. Don't parse ls. Your code will not work for files whose names contain whitespace.

    array1=( "${files}"*.png )
    
  3. Your array2 isn't an array; it's a string consisting of a sequence of file names separated by whitespace.

    array2=( $(find . ! -name 'PHOTO*') )
    

    Also, using find in a command substitution like this can fail for the same reason outlined in 2). Use an extended pattern instead (activated by running shopt -s extglob):

    array2=( !(PHOTO*) )
    
  4. To iterate over the files in an array, you first need to expand the array into a sequence of words, one element per word:

    for files in "${array2[@]}"; do
        rm -f "$files"
    done
    


Answered By - chepner
Answer Checked By - Robin (WPSolving Admin)