Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mac OS X Unix to find replace using regular expression

Tags:

unix

macos

this is my first question so apologies if this has been answered before. I have searched but cannot find what I am looking for.

I have a huge amount of text that has been exported from a database. For certain attribute content, I need to find each instance of a space followed by a capital letter and just replace the space with a semi-colon(;).

For example:

First one Second one Third one Fourth one

Should become:

First one;Second one;Third one;Fourth one

Using Unix (Mac OS X) The following just returns the whole line:

echo "First one Second one Third one Fourth one" | grep ' [A-Z]'

How would I achieve my desired outcome please? Any help or pointers would be very much appreciated. Thanks.

like image 607
intoto Avatar asked Sep 11 '25 12:09

intoto


1 Answers

Use sed for such task:

$ echo "First one Second one Third one Fourth one" | sed -Ee 's/ ([A-Z])/;\1/g'
First one;Second one;Third one;Fourth one
  • -E option is specified to use extended regular expression.

  • s/pattern/replace-string/g finds pattern and replace with the replace-string globally.
  • [A-Z] matches uppercase alphabet. by surrounding the pattern with (..), it can be referenced later in replace-string.
like image 116
falsetru Avatar answered Sep 15 '25 19:09

falsetru



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!