Reputation: 23
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.
Upvotes: 1
Views: 70
Reputation: 58351
This might work for you (GNU sed):
sed -E 'h;y/.-/__/;s/.*/\U&/;G;s/=.*=/=/' file
Make a copy of the current line.
Translate .
and -
to _
.
Capitalize the whole line.
Append the copy.
Remove the centre portion.
Upvotes: 1
Reputation: 133428
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:
=
awk
's default function named toupper
which will make $1(first field) upper case and save it into $1 itself.gsub
to substitute .
OR -
with _
in $1 as per requirement.1
which is idiomatic way to print a line in awk
.Upvotes: 2
Reputation: 626689
You can use
sed ':a;s/^\([^=]*\)[.-]\([^=]*\)/\U\1_\2/g;ta' file > newfile
Details:
:a
- sets an a
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 to a
label position upon successful replacement
_
+ Group 1See 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
Upvotes: 0