Jassi
Jassi

Reputation: 541

how to use regex under find command

I need to list all filenames which is having alien.digits digits can be anytime from 1 to many but it should not match if its the mixture of any other thing like alien.htm, alien.1php, alien.1234.pj.123, alien.123.12, alien.12.12p.234htm

I wrote: find home/jassi/ -name "alien.[0-9]*" But it is not working and its matching everything.

Any solution for that?

Upvotes: 0

Views: 1843

Answers (4)

Jassi
Jassi

Reputation: 541

It worked for me: find home/jassi/ type -f -regex ".*/alien.[0-9]+"

I had to provide type -f to check if it's a file , else it would show the directory also of the same name.

Thanks bmk. I just figured out and at the same time you responded exactly the same thing. Great!

Upvotes: 0

bmk
bmk

Reputation: 14137

I think what you want is

find home/jassi/ -regex ".*/alien\.[0-9]+"

With -name option you don't specify a regular expression but a glob pattern.

Be aware that find expects that the whole path is matched by the regular expression.

Upvotes: 2

Polynomial
Polynomial

Reputation: 28316

The * modifier means 0 or more of the previous match, and . means any character, which means it's matching alien.

Try this instead:

alien\.[0-9]+$

The + modifier means 1 or more of the previous match, and the . has been escaped to a literal character, and the $ on the end means "end of string".

You can also add a ^ to the start of the regex if you want to make sure that only files that exactly match your regex. The ^ character means "start of string", so ^alien\.[0-9]+$ will match alien.1234, but it won't match not_an_alien.1234.

Upvotes: 0

RePierre
RePierre

Reputation: 9566

Try this: find home/jassi/ -name "alien\.[0-9]+$" It will match all files that have alien. and end with at least one digit but nothing else than digits. The $ character means end of string.

Upvotes: 1

Related Questions