-2

I need to extract in linux bash from a string a set of characters which are included between a static string and the first number.

A simple example should be helpful:

Base string: hello-world-my_name-1.0.jar

Static string: hello-world-

Target: my_name

I'm trying with

ls *.jar | sed 's/(?<=hello-world-)(.+?(?=-[0-9]))/\1/'

but unfortunately I can't understand where I'm wrong

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • 1
    Please read [ask] and provide a [mre]. – baduker Sep 27 '22 at 10:51
  • Also, check [Learning Regular Expresions](https://stackoverflow.com/questions/4736/learning-regular-expressions) here at Stackoverflow. – baduker Sep 27 '22 at 10:52
  • Where is the string stored? In a variable, in a file? Bash or POSIX shell? Bash/shell only or using external binaries such as sed, grep, awk? – knittl Sep 27 '22 at 10:58

1 Answers1

0

Match everything, capture your middle string in a group and replace everything with the captured value:

printf 'hello-world-my_name-1.0.jar\n' | sed 's/hello-world-\([^0-9]*\).*/\1/'

Output:

my_name-

If the hyphen needs to be replaced too, match it outside the group; or remove it with a second pattern:

printf 'hello-world-my_name-1.0.jar\n' | sed 's/hello-world-\([^0-9]*\)-.*/\1/'
# or
printf 'hello-world-my_name-1.0.jar\n' | sed 's/hello-world-\([^0-9]*\).*/\1/;s/-$//'

Alternatively, if the middle string cannot contain hyphens, add it to the character class:

printf 'hello-world-my_name-1.0.jar\n' | sed 's/hello-world-\([^0-9-]*\).*/\1/'
knittl
  • 246,190
  • 53
  • 318
  • 364