Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct bash sed command syntax to get a correct substring

Tags:

regex

bash

sed

perl

Trying to get a sub-string from a:

foo-bar-8568887b6f-d95wk 1/1 Running 0 48m

to get a: foo-bar-8568887b6f-d95wk

using: sed 's/^.\((foo-bar)[^\s]+\).*$/\1/'

However that would return the whole string: foo-bar-8568887b6f-d95wk 1/1 Running 0 48m

What is the correct sed command in this case?

like image 268
0leg Avatar asked May 15 '26 13:05

0leg


1 Answers

There are a couple of issues:

  • . after ^ requires a single character to be present
  • (foo-bar) in the POSIX BRE pattern matches (foo-bar) but there are no parentheses in your string
  • [^\s] in a POSIX bracket expression matches a char other than \ and s, not a non-whitespace char
  • + in the POSIX BRE pattern matches a + char.

Use

sed -n 's/^.*\(foo-bar[^[:space:]]*\).*/\1/p'

Here,

  • -n - suppresses the default line output
  • s - substitution command
  • /^.*\(foo-bar[^[:space:]]*\).*/- matches start of the string, any 0+ chars, capturesfoo-barand 0 or more chars other than whitespace into Group 1 (\1`), and then matches the rest of the string
  • \1 - replaces the whole match with Group 1 contents
  • p - prints the result of the substitution.

Alternatively, consider an awk command that will work if the match is always expected at the start of the string:

awk '$0 ~ /^foo-bar/{print $1}'

See the online demo. It means that if the line starts with foo-bar ($0 ~ /^foo-bar/) awk will print Field 1 (the default field separator is whitespace, so you will get the substring from the start till the first whitespace).

like image 135
Wiktor Stribiżew Avatar answered May 17 '26 06:05

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!