EDITED: I need to use -E for extended regex.

I have a folder with this files (just an example):
directory structure

I'm trying to find all files that:

  1. Start and end with #. (e.g #hi.h#)
  2. End with ~. (e.g file.txt~)

I can find 1 condition files or 2 condition files, but i can't combine both in one regex.

$ find . -regex "./.*~"

$ find . -regex "./#.*#"

But this command is not working:

$ find . -regex "./(.*~$)|(#.*#)"

What am I doing wrong? how I can combine these regexes?

find . -regex "\./#.*#\|\./.*~"

Does this work for you?

| improve this answer | |

I need to use -E for extended regex.

Invoke find . -regextype help to learn available options. GNU find in my Debian supports few. This works:

find . -regextype posix-extended -regex '\./(.*~$|#.*#)'

Note I have debugged and simplified the regex a little (\./.*~$|\./#.*# would also work). Other options that work for me in this particular case: posix-egrep, egrep, posix-awk, awk, gnu-awk.

This command:

find . -regex '\./#.*#\|\./.*~'

where | is escaped works for me. Credits to the other answer. Proper escaping of ( and ) makes the following work as well:

find . -regex '\./\(.*~$\|#.*#\)'

without relying on extended regular expressions.

You don't have to compact the two expressions into one. If these work:

find . -regex '\./.*~'
find . -regex '\./#.*#'

then you can get files matching one regex or the other this way:

find . -regex '\./.*~' -o -regex '\./#.*#'

Be warned: Why does find in Linux skip expected results when -o is used? If you want to add more tests/actions before and/or after then you don't want this:

find . -test1 -test2 -regex '\./.*~' -o -regex '\./#.*#' -test3 …

but this:

find . -test1 -test2 '(' -regex '\./.*~' -o -regex '\./#.*#' ')' -test3 …
| improve this answer | |
  • 1
    Very nice answer! Just a short remark: Whenever using a more powerful tool, like a regular expression type providing more features, one has to ask the price, which will always be paid with either computation time or memory. For this reason I prefer the simplest tool that does the trick. In this case that means to avoid the -regextype parameter, to gain a 1/3 real-time speedup. – dirdi Oct 3 '19 at 15:19
  • regextype doesn't work on macOS – Elliott B Nov 13 '19 at 21:41

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.