-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

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Benjamin Allison
  • 2,134
  • 3
  • 30
  • 55
  • 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 Jan 15 '23 at 20:18
  • Start with looking at something like this: https://stackoverflow.com/q/918886/4961700 – Solar Mike Jan 15 '23 at 20:23

2 Answers2

3

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.

Wiimm
  • 2,971
  • 1
  • 15
  • 25
-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

  • It is useful to wait with the answer until the questioner has shown what he has done to answer the question himself. – Cyrus Jan 15 '23 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](https://wiki.bash-hackers.org/syntax/pe). And because this example is searching on `/`s instead of `-`s, it's not responsive to the question as-asked. – Charles Duffy Jan 15 '23 at 22:47