0leg
0leg

Reputation: 14144

Correct bash sed command syntax to get a correct substring

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?

Upvotes: 3

Views: 805

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626794

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).

Upvotes: 3

Related Questions