divinedragon divinedragon - 1 month ago 12
Linux Question

Replacement within the matched string with sed

I have a property file for java like below.

server.port=8080
spring.application.name=app1
spring.datasource.driver-class-name=org.mysql.jdbc.Driver


I want to convert the file to a linux equivalent property file like below.

SERVER_PORT=8080
SPRING_APPLICATION_NAME=app1
SPRING_DATASOURCE_DRIVER_CLASS_NAME=org.mysql.jdbc.Driver


I am using
sed
, and I am able to convert the property names with the following sed command.

sed "s/^\(.*\)=\(.*\)$/\U\1=\E\2/" application.properties


However, I am not able to figure out how to replace the dots(
.
) with underscore(
_
) character in the matched part(
\1
).

Can somebody help?

Answer

If perl is okay:

$ perl -pe 's/^.*=/\U$&/; s/^.*=/$&=~s|\.|_|gr/e' application.properties 
SERVER_PORT=8080
SPRING_APPLICATION_NAME=app1
SPRING_DATASOURCE_DRIVER-CLASS-NAME=org.mysql.jdbc.Driver
  • s/^.*=/$&=~s|\.|_|gr/e use another substitution for captured text ^.*=


With sed

$ sed 's/^.*=/\U&/; :a s/^\([^=]*\)\./\1_/g; ta' application.properties 
SERVER_PORT=8080
SPRING_APPLICATION_NAME=app1
SPRING_DATASOURCE_DRIVER-CLASS-NAME=org.mysql.jdbc.Driver
  • :a s/^\([^=]*\)\./\1_/g; ta replace . with _ until the text before . doesn't contain =


If both . and - before = needs to be changed to _, use [.-] instead of \. in both solutions