Search code examples
linuxbashrm

rm a file when there are similar names of files in directory?


Lets say that in a directory you have really long names similar to each other.

Is there a way to use rm browsing the directory to select the one you want to delete?

Maybe something similar to the way you browse a directory when you open it with vim...


Solution

  • You can do something along these lines, provided you have a version of xargs that supports the -d option:

    ls > list_of_files
    

    to create a file list_of_files that contains your filenames. Then edit this file (with, e.g., vim), deleting the files you want to keep, and leaving the files you want to delete. Then:

    < list_of_files xargs -d\\n -n1 echo rm --
    

    to remove the files in your list.

    Note that I used the: -n1 options and left echo: as is, this command is harmless. It will only show on your terminal which rm commands will be executed. If this looks good to you, remove -n1 and echo.

    Don't use this method if your xargs doesn't support the -d option, unless you thoroughly check that your filenames don't contain spaces, quotes, backslashes, and other funny characters.

    Also, make sure that, to begin with, your filenames don't contain newlines (and check that list_of_files looks good).