1

Working on a script where I need to take a string, and remove everything after the last occurence of a certain character. In this case a hyphen.

For example, This-is-a-filename-0001.jpg should result in This-is-a-filename

2
  • 1
    Please add to your question (no comment): What have you searched for, and what did you find? What have you tried, and how did it fail?
    – Cyrus
    Commented Jan 15, 2023 at 20:18
  • Start with looking at something like this: stackoverflow.com/q/918886/4961700
    – Solar Mike
    Commented Jan 15, 2023 at 20:23

2 Answers 2

5

You can cut strings in bash:

line="This-is-a-filename-0001.jpg"
echo "${line%-*}" # prints: This-is-a-filename

The %-*operator removes all beginning with the last hyphen.

-1

You're looking for a sed within your script, something close to what's below.

sed 's!/[^/]*$!/!'

Generally, I would say, please do research before posting a question like yours since it's relatively easy to find the answers

2
  • It is useful to wait with the answer until the questioner has shown what he has done to answer the question himself.
    – Cyrus
    Commented Jan 15, 2023 at 20:26
  • Why would you use any external command for something the shell can do built-in? This is much slower to run than using built-in parameter expansion. And because this example is searching on /s instead of -s, it's not responsive to the question as-asked. Commented Jan 15, 2023 at 22:47

Not the answer you're looking for? Browse other questions tagged or ask your own question.