0

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 "./.*~"
./lld~

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

But this command is not working:

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

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

2 Answers 2

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

Does this work for you?

1

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 …
2
  • 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
    Commented Oct 3, 2019 at 15:19
  • regextype doesn't work on macOS
    – Elliott B
    Commented Nov 13, 2019 at 21:41

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .