2

We have the following configuration file

more /tmp/file

delete.topic.enable=true
broker.id=-1
advertised.listeners=null
.
.
.

We need to convert all syntax above as the following:

  1. Change the characters until “=” separator to uppercase characters
  2. Add KAFKA_ in the beginning of each line
  3. Replaces each dot “.” To under line “_” until the “=” separator

Example of expected results

KAFKA_DELETE_TOPIC_ENABLE=true
KAFKA_BROKER_ID=-1
KAFKA_ADVERTISED_LISTENERS=null
.
.
.

Any sed suggestion for this changing ?

We try this ,

but this also convert the charterers after the “=” separator ( not as should be ) , and also we not sure how we can add the KAFKA_ in the beginning

sed 's/[a-z]/\U&/g'  /tmp/file | sed s'/\./_/g'

DELETE_TOPIC_ENABLE=TRUE
BROKER_ID=-1
ADVERTISED_LISTENERS=NULL
.
.
1
  • 3
    Since you said Replaces each dot “.” To under line “_” until the “=” separator you should include a case where there are .s after the = in your sample input/output for us to test against as it'd be easy to assume a simple s/\./_/g would suffice and if that was tested with your current sample input/output we wouldn't know that it failed the until the “=” separator part of your requirement.
    – Ed Morton
    Apr 5 '20 at 20:46
1

With GNU awk for the 3rd arg to match():

$ awk 'match($0,/([^=]+)(.*)/,a){ gsub(/\./,"_",a[1]); print "KAFKA_" toupper(a[1]) a[2]}' file
KAFKA_DELETE_TOPIC_ENABLE=true
KAFKA_BROKER_ID=-1
KAFKA_ADVERTISED_LISTENERS=null

With any awk:

$ awk 'match($0,/[^=]+/){ tag=substr($0,1,RLENGTH); gsub(/\./,"_",tag); print "KAFKA_" toupper(tag) substr($0,1+RLENGTH)}' file
KAFKA_DELETE_TOPIC_ENABLE=true
KAFKA_BROKER_ID=-1
KAFKA_ADVERTISED_LISTENERS=null
0
awk -F "=" 'OFS="="{gsub(/\./,"_",$1);print "KAFKA_"toupper($1)"="$2}' FILE

OUTPUT

KAFKA_DELETE_TOPIC_ENABLE=true
KAFKA_BROKER_ID=-1
KAFKA_ADVERTISED_LISTENERS=nul1

python

#!/usr/bin/python
import re
k=open('file1','r')
for i in k:
    y=i.split('=')
    z=y[0].upper().replace(".","_")+"="+y[1]
    print "KAFKA_{0}".format(z).strip()

output

KAFKA_DELETE_TOPIC_ENABLE=true
KAFKA_BROKER_ID=-1
KAFKA_ADVERTISED_LISTENERS=null
0

perl one-liner:

perl -pe 's/^([^=]+)/KAFKA_\U$1/; s/\.(?=[^=]*=)/_/g' file

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.