Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sed: replace from the last occurrence of "-" till EOL

Tags:

regex

sed

My problem

I have a file with items, one per line. The item contains at least one dash, and I would like to remove the last dash and the words that follow. For example:

item asdkalqndla-asdnkfsv-324we-blueray
item asda-vbght564e-dfg-redapple
item gefdsc-fgy-543-5trr-floatingvanilla

Should give:

item asdkalqndla-asdnkfsv-324we
item asda-vbght564e-dfg
item gefdsc-fgy-543-5trr

What have I tried

sed 's/\-.*$//' lines.txt

Which gives

item asdkalqndla
item asda
item gefdsc

Because the regex is greedy, and consumes everything from the first dash onwards.

My question

How can I remove all characters from the last - in a string till EOL?

like image 822
Adam Matan Avatar asked Dec 13 '25 06:12

Adam Matan


2 Answers

With awk:

$ awk '{sub(/-[^-]*$/,""); print}' file
item asdkalqndla-asdnkfsv-324we
item asda-vbght564e-dfg
item gefdsc-fgy-543-5trr
like image 181
dawg Avatar answered Dec 15 '25 17:12

dawg


Simple negation using ^\- solved the problem:

$ sed 's/\-[^\-]*$//' lines.txt
item asdkalqndla-asdnkfsv-324we
item asda-vbght564e-dfg
item gefdsc-fgy-543-5trr

This way, sed replaces a dash followed by anything-but-dash till the end of the line.

like image 29
Adam Matan Avatar answered Dec 15 '25 16:12

Adam Matan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!