Sed – Replace Text Between Specific Patterns

linuxsedstringtext processing

I've been trying with sed, and googling for the whole morning, and I can't seem to get this to work.

Is it possible with sed to lowercase text between two specific characters:

i.e.

SOMENAME=WOODSTOCK,
SOMEOTHERNAME=JIMMY,

can I lowercase WOODSTOCK and JIMMY (to woodstock and jimmy) on the basis they are between = and ,?

Best Answer

It is possible with GNU sed. Choose one of these two forms based on the greediness of the replacement.

sed 's|=.*,|\L&|' file
sed 's|=[^,]*,|\L&|' file

As the manual states, "\L turns the replacement to lowercase until a \U or \E is found". & is the text matched by the regex.


I have modified the sample file to show that you should wisely choose between the geedy =.*, and the non-greedy =[^,]*, regexes:

$ cat file
SOMENAME=WOODSTOCK,
SOMEOTHERNAME2=JIMMY,WOODSTOCK,FINISH
$ sed 's|=.*,|\L&|' file
SOMENAME=woodstock,
SOMEOTHERNAME2=jimmy,woodstock,FINISH
$ sed 's|=[^,]*,|\L&|' file
SOMENAME=woodstock,
SOMEOTHERNAME2=jimmy,WOODSTOCK,FINISH
Related Question