Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sed expression that converts some matches to uppercase

Tags:

sed

This sed expression converts an input string into a two-line output string. Each of the two output lines are composed of substrings from the input. The first line needs to be convered into upper case:

s:random_stuff\(choice1\|choice2\){\([^}]*\)}:\U\1\n\2:

The aim is to convert

random_stuff_choice1{This is a sentence that MAY contain AnyThing}
random_stuff_choice2{This is another similar sentence}

into

CHOICE1
This is a sentence that MAY contain AnyThing
CHOICE2
This is another similar sentence

The problem I have is that \U aplies to everything following it so the second line is also uppercased. Is it possible to make \U apply to the first match only ?

like image 324
starfry Avatar asked Feb 17 '23 09:02

starfry


1 Answers

With sed:

$ sed 's/.*\(choice[0-9]\+\){\([^}]*\)}/\U\1\n\E\2/' file
CHOICE1
This is a sentence that MAY contain AnyThing
CHOICE2
This is another similar sentence

With awk:

$ awk -F'{|}' 'gsub(/.*_/,""){print toupper($1)"\n"$2}' file
CHOICE1
This is a sentence that MAY contain AnyThing
CHOICE2
This is another similar sentence
like image 162
Chris Seymour Avatar answered Feb 23 '23 15:02

Chris Seymour