Home > Enterprise >  How to get only one part of the string without the end in bash
How to get only one part of the string without the end in bash

Time:11-22

I want to get only one part of the string new-profile-input, the part that I need is: "new-profile" without the "-input".

I tried like this:

cat automatization_test.sh |  grep -oh "\new-profile-input\w*" | grep -o "\-input\w*"

But, I get output:

-input

But, I need the first part not the last part of the string. Please note that the "new-profile" will always change, so that is why I have to focus on removing "-input" instead of getting only "new-profile".

Thank you in advance,

CodePudding user response:

Using sed, you can exclude everything after the last - slash where -input would be in your example string.

$ sed 's/\(.*\)-.*/\1/' automatization_test.sh
new-profile

CodePudding user response:

If supported, you can use use -P for Perl-compatible regular expressions with a positive lookahead to assert -profile to the right and match word characters with a possible hyphen in between.

Note that instead of using cat, you can also add the file at the end of the grep command instead.

grep -oP '\w (?:-\w )*(?=-input\b)' automatization_test.sh

See a regex demo for the match.

Or for a broader match assert whitespace boundaries to the left and right and match non whitespace chars:

grep -oP '(?<!\S)\S (?=-input(?!\S))' automatization_test.sh

See a regex demo for the match.


Or as an alternative using gnu-awk with a pattern and a capture group:

awk 'match($0, /(\w (-\w )*)-input\>/, a) {print a[1]}' automatization_test.sh
  • Related