Is there a way to use sed (with potential other command) to transform all the keys in a file that lists key-values like that :
a.key.one-example=a_value_one
a.key.two-example=a_value_two
and I want that
A_KEY_ONE_EXAMPLE=a_value_one
A_KEY_TWO_EXAMPLE=a_value_two
What I did so far :
sed -e 's/^[^=]*/\U&/'
it produced this :
A.KEY.ONE-EXAMPLE=a_value_one
A.KEY.TWO-EXAMPLE=a_value_two
But I still need to replace the "." and "-" on left part of the "=". I don't think it is the right way to do it.
CodePudding user response:
It should be done very easily done in awk
. awk
is the better tool IMHO for this task, it keeps it simple and easy.
awk 'BEGIN{FS=OFS="="} {$1=toupper($1);gsub(/[.-]/,"_",$1)} 1' Input_file
Simple explanation:
- Make field separator and output field separator as
=
- Then use
awk
's default function namedtoupper
which will make $1(first field) upper case and save it into $1 itself. - Using
gsub
to substitute.
OR-
with_
in $1 as per requirement. - use
1
which is idiomatic way to print a line inawk
.
CodePudding user response:
You can use
sed ':a;s/^\([^=]*\)[.-]\([^=]*\)/\U\1_\2/g;ta' file > newfile
Details:
:a
- sets ana
labels/^\([^=]*\)[.-]\([^=]*\)/\U\1_\2/g
- replaces^\([^=]*\)[.-]\([^=]*\)
pattern that matches^
- start of string\([^=]*\)
- Group 1 (\1
): any zero or more chars other than=
[.-]
- a dot or hyphen\([^=]*\)
- Group 2 (\2
): any zero or more chars other than=
ta
- jumps back toa
label position upon successful replacement
and replaces with Group 2_
Group 1
See the online demo:
#!/bin/bash
s='a.key.one-example=a_value_one
a.key.two-example=a_value_two'
sed ':a;s/^\([^=]*\)[.-]\([^=]*\)/\U\1_\2/g;ta' <<< "$s"
Output:
A_KEY_ONE_EXAMPLE=a_value_one
A_KEY_TWO_EXAMPLE=a_value_two