Justin Gagnon
Justin Gagnon

Reputation: 193

How to have SED remove all characters between a hypen and the file extension

I have been trying with no luck to change this

'Simple' week 1-117067638.mp3

into this

'Simple' week 1.mp3

However when I use the command sed 's/\(-\).*\(.mp3\)//' I get

'Simple' week 1

How do I keep my file extension? If you could explain the command you use it would be great so that I can learn from this instead of just getting an answer.

Upvotes: 0

Views: 34

Answers (2)

Avinash Raj
Avinash Raj

Reputation: 174696

You don't need to have a capturing group.

$ echo "'Simple' week 1-117067638.mp3" | sed 's/-.*\.mp3/.mp3/g'
'Simple' week 1.mp3

OR

$ echo "'Simple' week 1-117067638.mp3" | sed 's/-.*\(\.mp3\)/\1/g'
'Simple' week 1.mp3

What's wrong with your code?

sed 's/\(-\).*\(.mp3\)//'

sed would replace all the matched characters with the characters in the replacement part. So \(-\).*\(.mp3\) matches all the characters from - to .mp3 (you must need to escape the dot in-order to match a literal dot). You're replacing all the matched characters with an empty string. So .mp3 also got removed. In-order to avoid this, add .mp3 to the replacement part. In basic sed, capturing groups are represented by \(..\). This capturing group is used to capture characters which are to be referenced later.

Upvotes: 1

John1024
John1024

Reputation: 113814

This task can also be done just in bash without calling sed:

$ fname="'Simple' week 1-117067638.mp3"
$ fname="${fname/-*/}.mp3"
$ echo "$fname"
'Simple' week 1.mp3

Upvotes: 0

Related Questions