Removing Files with specific ending. Need something more specific

I’m trying to purge all thumbnails created by WordPress because of a CMS switchover that I’m planning.

find  -name *-*x*.* | xargs rm -f

But I dont know bash or regex well enough to figure out how to add a bit more specifity such as only the following will be removed

Read More

All generated files have the syntax of

<img-name>-<width:integer>x<height:integer>.<file-ext> syntax

Related posts

Leave a Reply

3 comments

  1. You didn’t quote or escape all your wildcards, so the shell will try to expand them before find executes.

    Quoting it should work

    find -name '*-*x*.*'| xargs echo rm -f
    

    Remove the echo when you’re satisfied it works. You could also check that two of the fields are numbers by switching to -regex, but not sure if you need/want that here.

    regex soultion

    find -regex '^.*/[A-Za-z]+-[0-9]+x[0-9]+.[A-Za-z]+$' | xargs echo rm -f
    

    Note: I’m assuming img-name and file-ext can only contain letters

  2. You can try this:

    find -type f |  grep -P 'w+-d+xd+.w+$' | xargs rm
    

    If you have spaces in the path:

    find -type f  |  grep -P 'w+-d+xd+.w+$' | sed -re 's/(s)/\1/g' | xargs rm
    

    Example:

    find -type f |  grep -P 'w+-d+xd+.w+$' | sed -re 's/(s)/\1/g' | xargs ls -l
    -rw-rw-r-- 1 tiago tiago 0 Jun 22 15:14 ./image-800x600.png
    -rw-rw-r-- 1 tiago tiago 0 Jun 22 15:17 ./test 2/test 3/image-800x600.png
    
  3. The below GNU find command will remove all the files which contain this <img-name>-<width:integer>x<height:integer>.<file-ext> syntax string. And also i assumed that the corresponding files has . in their file-names.

    find . -name "*.*" -type f -exec grep -l '<img-name>-<width:integer>x<height:integer>.<file-ext> syntax' {} ; | xargs rm -f
    

    Explanation:

    • . Directory in which find operation is going to takeplace.(. represnts your current directory)

    • -name "*.*" File must have dot in their file-names.

    • -type f Only files.

    • -exec grep -l '<img-name>-<width:integer>x<height:integer>.<file-ext> syntax' {} print the file names which contain the above mentioned pattern.

    • xargs rm -f For each founded files, the filename was fed into xargs and it got removed.