1

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.

Sunderam Dubey
  • 1
  • 11
  • 20
  • 40
DenisB
  • 29
  • 4
  • 1
    OP knows very well how to use `-regex` option in `find`. Issue is in the regex pattern not in the command. – anubhava Oct 06 '22 at 05:51
  • 1
    You have forgotten to quote your patterns. What is confusing, is that your `find` statement should produce an error, because the `|` is interpreted as pipe symbol. – user1934428 Oct 06 '22 at 07:48

2 Answers2

1

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.

anubhava
  • 761,203
  • 64
  • 569
  • 643
1

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' \)
blhsing
  • 91,368
  • 6
  • 71
  • 106
  • 1
    Yes. I tried, but it doesn't good for me because I take regex from external json (I do this in the pipeline in groovy and read regex from json file) – DenisB Oct 06 '22 at 06:46