bosadjo
bosadjo

Reputation: 57

Bash: Regex match betwen first occurrence of characters

Input:

p45-322-16.jpg

Desired output:

p45

I'm trying to make a bash script with grep or awk or sed or something that could run on a bash shell.

Currently I'm stuck with this:

echo "p45-322-16.jpg" | sed 's/\(.*\)-.*/\1/'

Output:

p45-322

Upvotes: 2

Views: 5496

Answers (3)

RaviTezu
RaviTezu

Reputation: 3125

You can use cut command: echo "p45-322-16.jpg" | cut -d"-" -f1

Upvotes: 3

Ewan Mellor
Ewan Mellor

Reputation: 6857

echo "p45-322-16.jpg" | sed 's/\([^-]*\).*/\1/'

The .* part of your regex is greedy, so it reads as far as possible so that the regex still matches. This means it claims everything up to the last -.

Use [^-]* to match everything until a -.

Upvotes: 2

aghast
aghast

Reputation: 15310

You need to limit what you will accept. Right now, you are accepting too much by using ., and the greedy-by-default nature of regexes is consuming too many characters.

Try either limiting the accepted characters to digits only, or specifically excluding the dash:

\([0-9]*\).*

\([^-]*\).*

Upvotes: 2

Related Questions