Home > Mobile >  sed search and replace only before a char
sed search and replace only before a char

Time:10-13

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 named toupper 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 in awk.

CodePudding user response:

You can use

sed ':a;s/^\([^=]*\)[.-]\([^=]*\)/\U\1_\2/g;ta' file > newfile

Details:

  • :a - sets an a label
  • s/^\([^=]*\)[.-]\([^=]*\)/\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
    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
  • Related