1

I have a puzzle to solve which I could not do on my own. I believe it may be a simple one for others. I was trying to solve in a one liner.

I have following strings:

Tree-Forest
Vegetable-fruit-Garden
Fish-Frog-Ponds
Chicken-Duck-Farm

I need to extract the part before last -, like (omitting the last - and the string after that):

Tree
Vegetable-fruit
Fish-Frog
Chicken-Duck 

Please help.

1
  • Have you read the bash documentation on Parameter Expansion? It shows all the operations you can perform, including this one. Commented May 10, 2015 at 18:22

1 Answer 1

1

Using BASH string manipulations:

s='Tree-Forest Vegetable-fruit-Garden Fish-Frog-Ponds Chicken-Duck-Farm'
echo "${s%-*}"
Tree-Forest Vegetable-fruit-Garden Fish-Frog-Ponds Chicken-Duck

After edited question it seems you're editing a file then you can use sed also:

sed 's/-[^-]*$//' file
Tree
Vegetable-fruit
Fish-Frog
Chicken-Duck
Sign up to request clarification or add additional context in comments.

7 Comments

Where does the question mention a file?
Before editing I thought it is all in one single string but now it says I have following strings. Now difficult to see how strings are available in a block like this unless there is file. If not a file then sed 's/-[^-]*$//' <<< "$input"
Maybe in a for or while loop that sets the variable to each string.
OP says I was trying to solve in a one liner and doesn't provide details then.
Excellent, thanks a lot for solving this. Please explain what [^-]*$ means?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.