Regex to match everything before hypen - multiple match

Viewed 113

I got this string:

scQA00-psql11 scQA00-psql21 scQA01-psql2 scQA00-psql21
scqa00-psql01 scqa00-psql11 scqa00-psql21

I want to match only:

scQA00 scQA00 scQA01 scQA00
scqa00 scqa00 scqa00

I tried with: [^-]+ but cannot get any further than this :(

I tried also (.*?)(?=-)+

But it match only first occurrence.

How could i match everything before hyphen but to ignore spaces?

1 Answers

If you want to extract all substrings consisting of non-whitespace chars before -, you may use

grep -Po '[^\s-]+(?=-)' file

See the regex demo. The [^\s-]+(?=-) pattern matches any one or more chars other than whitespace and -, followed with a -.

If you just need to remove parts of strings starting with - and until the next whitespace or end of string, you may use sed:

sed -E 's/-[^[:space:]]+//g' file

Here, -[^[:space:]]+ matches a - and then one or more chars other than whitespace.

See the online demo:

text='scQA00-psql11 scQA00-psql21 scQA01-psql2 scQA00-psql21
scqa00-psql01 scqa00-psql11 scqa00-psql21'
grep -Po '[^\s-]+(?=-)' <<< "$text"
# scQA00
# scQA00
# scQA01
# scQA00
# scqa00
# scqa00
# scqa00
sed -E 's/-[^[:space:]]+//g' <<< "$text"
# scQA00 scQA00 scQA01 scQA00
# scqa00 scqa00 scqa00
Related