Home > Enterprise >  How to find with regex and match by pattern after last slash
How to find with regex and match by pattern after last slash

Time:10-06

On Linux server I have several files in folder and my question is:

How to find with regex only filename(s), started with foo or bar and ended with .properties. But not any.properties. Only foo-service .properties and bar-service .properties

/home/user/foo-service/src/main/resources/any.properties

/home/user/foo-service/src/main/resources/foo-service.properties

/home/user/foo-service/src/main/resources/bar-service.properties

Try to find with string:

find /home/user/foo-service/src/main/resources/ -maxdepth 1 \
-regextype posix-extended  -regex .*(foo|bar).*\.properties

but in result I have all 3 strings, because foo exists in the path (/foo-service/)

I want to find only after the last slash in the path and as a result I need absolute path to the file.

CodePudding user response:

You can use this command:

find /home/user/foo-service/src/main/resources/ -maxdepth 1 \
  -regextype posix-extended  -regex '.*/(foo|bar)[^/]*\.properties$'

Here, (foo|bar)[^/]*\.properties$ will match any file name that starts with foo or bar and ends with .properties while matching 0 or more of any char that is not / after foo or bar.

So this will match:

/home/user/foo-service/src/main/resources/foo-service.properties
/home/user/foo-service/src/main/resources/bar-service.properties

but won't match:

/home/user/foo-service/src/main/resources/any.properties

Since we have a / character after /foo in last path.

CodePudding user response:

You can use the -name option instead to match just the base file name rather than having to deal with the entire path name. Use the -o operator to match both prefixes:

find /home/user/foo-service/src/main/resources/ -maxdepth 1 \
    \( -name 'foo*.properties' -o -name 'bar*.properties' \)
  • Related