0

what is the regular expression to capture the folder name with this structure

x.x.x.x-x ( x - integer number )

 ls /usr/hdp | .....
 2.6.0.3-8  current HG_MASTER 2.4.3 34.1 45-995

expected output

2.6.0.3-8



ls -lh /usr/hdp/
total 8.0K
drwxr-xr-x. 27 root root 4.0K Jan  1 15:24 2.6.0.3-8
jango
  • 423

4 Answers4

1

You need to use find instead. For exact match use pattern:

find /usr/hdp -regextype sed -regex "\/usr\/hdp\/[0-9]*\.[0-9]*\.[0-9]*\.[0-9]*-[0-9]*"

If you need any files with only digits, . and - symbols in names try:

find /usr/hdp -regextype sed -regex "\/usr\/hdp\/[.0-9-]*"
1
find . -type d -regextype posix-egrep -regex '^./([0-9]+[.]){3}[0-9]+[-][0-9]+'

Use find and then the regextype flag to set the reg expression syntax to egrep. Use -regex to check against 3 digits and a "dot" and then a digit a "dash" and a digit.

If the digits are more than one character, you will need + after each digit.

1

Since you tagged , you can actually do this with the shell's filename matching, using extended globs:

$ shopt -s extglob
$ touch /some/path/{2.6.0.3-8,22.66.0.333-8,foobar}
$ printf "%s\n" /some/path/+([0-9]).+([0-9]).+([0-9]).+([0-9])-+([0-9])
/some/path/22.66.0.333-8
/some/path/2.6.0.3-8

The pattern there works like more common things like * or *.png, so you can just stick the fixed parts like paths in it. Add a trailing slash / to only match directories. (the slash does appear in the output too, though.)

In ERE regex, the pattern is the same as [0-9]+\.[0-9]+\.[0-9]+\.[0-9]+-[0-9]+. A fuzzier version would just check for the allowed characters, like +([-.0-9]) (or [-.0-9]+ in ERE), but that of course would also match e.g. 123..456.

If you want to just print the filenames, find might be easier, but if you want to run a command on them, then a shell loop is also an option (along with find -exec).

ilkkachu
  • 138,973
-1
ls /usr/hdp | egrep '[0-9]+.[0-9]+.[0-9]+.[0-9]+-[0-9]+'