Is there a way to find and remove files with a pattern like this (where the pattern is only that there are two underscores in the file name, separated by letters or numbers)

ex. /file_name_name

I tried to use find . -name '*_*_' -delete to find those files, but no luck. Perhaps because the files are symlinks to directories?

  • 2
    If you don't use -delete, does it return the files? – Nasir Riley Apr 8 at 21:59
  • It does not sort out the files with that pattern, it shows any file that has an underscore and letters (like this- /1_name). I just want the files with two underscores separated with letters... – David Norden Apr 8 at 22:10
  • 1
    If I'm reading your intentions correctly, you want to find filenames that have two underscores in them; your initial effort is probably failing because you're asking that the filename ends with an underscore -- you'd want to add a trailing *. You'd also want to test to see whether a file named file__two-underscores counts and is matched, or not. – Jeff Schaller Apr 9 at 0:32
  • Thanks, you are completely right! It is working now. – David Norden Apr 9 at 7:46

Your filename globbing pattern is almost correct for detecting names that have at least two underscores, but you are forcing the names to have an underscore at the very end.

You should be ok if you just add a final * at the end of the pattern:

$ find . -name '*_*_*'

To explicitly not match names with more than two underscores:

$ find . -name '*_*_*' ! -name '*_*_*_*'

The second part here, -name '*_*_*_*', would match any name with three or more underscores, and the preceding ! would negate the sense of the match.

Note that a find expression without -type will match the names of any type of file, that is, it may match the names of directories, named pipes, sockets, device files etc.

To additionally only match regular files add -type f, or you could use ! -type d to avoid matching directory names. Use -type l to to match symbolic links.

The final find command may look like:

find . -type l -name '*_*_*' ! -name '*_*_*_*' -delete

This would remove symbolic links found in the current directory, or below, whose names include exactly two underscores. The targets of the symbolic links would not be affected, unless they themselves are symbolic links with names that match the criteria and are located under the current directory.

  • Super! Thanks a lot, that worked like a charm! – David Norden Apr 9 at 7:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.