Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace characters using regex grouping with sed

I have a text file that is like this:

FOO BAR PIPPO PLUTO 31337 1010
FOOZ BAZ 130
VERY LONG LINE LIKE THIS THEN A NUMBER LIKE 42

I need to turn it into:

FOO-BAR-PIPPO-PLUTO 31337 1010
FOOZ-BAZ 130
VERY-LONG-LINE-LIKE-THIS-THEN-A-NUMBER-LIKE 42

The best I could do is:

sed -re 's/([A-Z]+)( )([A-Z]+)/\1-\3/g'

but the output is

FOO-BAR PIPPO-PLUTO 31337 1010
FOOZ-BAZ 130
VERY-LONG LINE-LIKE THIS-THEN A-NUMBER LIKE 42

Close, but no cigar. Any idea on why my regex doesn't work?

like image 782
molok Avatar asked Dec 05 '25 14:12

molok


1 Answers

You can't have overlapping matches. "BAR PIPPO" isn't detected because "BAR" was already consumed when matching "FOO BAR".

FOO BAR PIPPO PLUTO 31337 1010
------- ===========
   1         2

Try this instead:

$ sed -re 's/ ([A-Z])/-\1/g'

Note that this doesn't have overlapping matches:

FOO BAR PIPPO PLUTO 31337 1010
   --  ==    --
   1   2     3
like image 137
Mark Byers Avatar answered Dec 07 '25 06:12

Mark Byers



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!