简体   繁体   中英

Linux find command: searching for a filename containing parentheses

I need to find files with filenames like this:

<some regex-matched text> (1).<some regex-matched text>

ie I want to search for filenames containing

  • text ending in a space
  • then an opening bracket (parenthesis)
  • followed by the numeral 1
  • followed by a closing bracket
  • possibly followed by a dot followed by some more text...

I first went find . -regex '.* \\(1\\)\\..*' find . -regex '.* \\(1\\)\\..*' . But the brackets are sort of ignored: files matching .* 1\\..* are returned.

In the course of my attempt to find an answer I found this page covering Linux find . Here I find this phrase:

"Grouping is performed with backslashes followed by parentheses '\\(', '\\)'."

[NB to show you the reader a single backslash, as shown in that page, I have doubled the backslashes to write the single backslashes above!]

I wasn't sure what to make of that, ie how to escape ordinary brackets in that case. I thought maybe doubling up the backslashes in the find expression might work, but it didn't.

Even if I try to do it without using a regex, find seems to have some problems with brackets and/or a dot in this place:

mike@M17A .../accounts $  find . -name *(1).pdf
[... finds stuff OK]
mike@M17A .../accounts $  find . -name *(1).*
find: paths must precede expression: ..
Usage: find [-H] [-L] [-P] [-Olevel] [-D help|tree|search|stat|rates|opt|exec|time] [path...] [expression]
mike@M17A .../accounts $  find . -name *(1)\.*
find: paths must precede expression: ..
Usage: find [-H] [-L] [-P] [-Olevel] [-D help|tree|search|stat|rates|opt|exec|time] [path...] [expression]

NB putting a space after in the initial * in these attempts also fails...

That is because you don't need to escape these parenthesis. This should work :

find . -regex '.* (1)\(\..*\)?'

Though a capture group is used (escaped parenthesis) \\(\\..*\\) so that we can make the last match optional ( possibly followed by a dot followed by some more text ) with ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM