I would like to run the find
command and get some of the files/directories in the desktop directory using regex
option of the command with the symbol caret ^
As you know the caret ^
matches the beginning of a line, and I would like to get all the files/directories starting with the letter t
; I used the following command find . -regex "^./t"
, but as it turned out, it will only match the file/folder whose name is a simple t!
I know that the regex will match the whole path
and not only the file name
. But why all of these do not match since they start with ./t
.
./tcpdump.txt
./t.txt
./test.sh
./trade.txt
./torbrowser.desktop
./token.txt
PS: This regex worked for me, ^./t.*
, but still unable to understand the behavior of caret in the original command
The fact that the regex always matches the whole path means the caret and dollar sign are redundant: The whole path must match, not just its substring. Or, you can always imagine the regex starts with a caret and ends with a dollar sign, even if you don't type them.
The
-regex
option expects a pattern that matches the entire path. Seeman find
:The caret is pointless in this context since as explained above, the
-regex
will have to match everything, so essentially, the^
and$
are implied.You gave it
^./t
which means "look for any character" (remember that the.
means "any character" in regular expressions, it doesn't mean a literal.
) followed by a/
and then the single lettert
and nothing else.What you need here is the
-name
operand, which takes globs and not regular expressions, and only matches the file's name, not the entire path. So to find all files/dirs whose name begins with at
, use:The glob
t*
means "t followed by 0 or more characters". If you really want to do it with-regex
, although that only makes it more complicated, you would need to specify that you allow anything to come after thet
, like this:That regex means "match as many characters as you can (including 0) until the last
/
and then at
followed by anything else.