molwiko
molwiko

Reputation: 343

Linux command line regex

I would like to search into directory for all files end by .m for string like @"LBL_18989" @"LBL_15459" , @"LBL_14359" ...

My command is :

find . type f -name \*.m | grep '@"LBL_[[0-9]"]+' 

but it does not give the expected result.

Upvotes: 0

Views: 1485

Answers (2)

geoO
geoO

Reputation: 5802

Your code runs for me. However, the regular expression you stated in the question will match a lot more than just the filenames in your example list. This can be a problem if you are looking to see if your filenames need name validation because some will validate that really shouldn't. Your regex pattern

grep '@"LBL_[[0-9]"]+'

also matches filenames such as

  1. @"LBL_"
  2. @"LBL_2"
  3. @"LBL_3"3"
  4. @"LBL_"4

If your list is really representative I would instead use

grep '@"LBL_[[0-9]]+"'

and move the quote character to after the plus, at the end of the pattern. You can use grep and maybe that's your use case, but if you use egrep or grep with the -E switch you get to use the [[:digit:]] class. POSIX.2 frowns on ranges in a bracket expression using the dash character. From the POSIX specification: "Ranges are very collating-sequence-dependent, and portable programs should avoid relying on them."

Upvotes: 0

jordanm
jordanm

Reputation: 34974

You should always quote your arguments. Your -name pattern for find contains an "*", which means the shell will try to expand it as a glob before passing it to find. You can also use -regex instead of piping the output of find to grep.

find . -type f -regex '@"LBL_[[:digit:]"]+'

Based on jdi's comment, you may be wanted to search the contents of those files for the given regex. If so, you can use the following:

find . type f -name '*.m' -exec grep -E '@"LBL_[[:digit:]"]+' /dev/null {} +

Upvotes: 3

Related Questions