skip to Main Content

I have a list of about 200 image file names. On the web server there are multiple instances of files with these file names within a subfolder structure within one directory.

Is there a command I can run to find all instances of these file names and delete them?

example of file names

  • image-488363450-1.jpg
  • somename-186758341-1.jpg
  • randomname-588968004-1.jpg
  • blabla124405236-1-1.jpg
  • someimage_MEDIUM.jpg

2

Answers


  1. find /path/to/files -type f -name "image*" -exec rm -f {} ;
    
    • name “FILE-TO-FIND” : File pattern.
    • exec rm -rf {} ; : Delete all files matched by file pattern.
    • type f : Only match files and do not include directory names.

    (this is actually from here)

    Login or Signup to reply.
  2. Assuming that the file “badFiles” file holds a list of filenames that you would like to delete, and “myDirs” holds a list of subdirectories in which they could be, the following should work:

    for file in `cat badFiles`
    do
      for dir in `cat myDirs`
      do
        [ -f ${dir}/${file} ] && rm ${dir}/${file}
      done
    done
    

    If the list of directories includes all subdirectories from your current working directory, then the following should work without creating the myDirs file:

    for file in `cat badFiles`
    do
      for dir in *
      do
        [ -d ${dir} ] && [ -f ${dir}/${file} ] && rm ${dir}/${file}
      done
    done
    

    To call this over SSH, you can put the contents of the below script into a file (in this example, I will use the location ${HOME}/bin/killImages.sh):

    Edit ~/bin/killImages.sh, and use the contents below. Once complete, write and save.

    #!/bin/bash
    cd $1
    for file in `cat ~/badFiles`
    do
      for dir in *
      do
        [ -d ${dir} ] && [ -f ${dir}/${file} ] && rm ${dir}/${file}
      done
    done
    

    Then make your script executable:

    chmod 700 ~/bin/killImages.sh
    

    Then on your local system, execute:

    ssh <user>@<hostname> "bin/killImages.sh /path/to/base/html"
    

    If you need to manually upload the list of bad files first, you would simply scp this into place before kicking off the script:

    scp badFiles <user>@<hostname>:.
    ssh <user>@<hostname> "bin/killImages.sh /path/to/base/html"
    

    Hope this helps.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search