substitution grouping

If you need so-called group replacements, every group has to be put in round brackets (); the brackets must be escaped, so you get \(\)

Consider the file sites.txt

less sites.txt

AndreyOlegovich.ru IT
Aviasales, Travel
Booking.com ,Hotels
Hotellook, Hotels
TopBicycle.ru, Bicycles

Let us convert the site names to upper case

sed 's/\([^,]*\)/\U\1/' sites.txt

ANDREYOLEGOVICH.RU, IT
AVIASALES, Travel
BOOKING.COM, Hotels
HOTELLOOK, Hotels
TOPBICYCLE.RU, Bicycles

Let us look in detail:

Inside \(\) the first group on which the action (replacement) is performed

\([^,]*\)

[^,]* means an unlimited number of non-commas

As soon as the first comma is met the group is formed; if the line has no comma the whole line is selected.

\U means convert to upper case

&92;1 means do it with the first group. So far we have only one group.

To work with the second group, after the first one you have to put , \(\)

There can be many groups. The syntax is as follows:

\(\), \(\), \(\), \(\)

They all have to be on the left side of the expression

/\(\), \(\), \(\), \(\) / /

sed 's/\([^,]*\),\([^,]*\)/\U\1\L\2/' sites.txt

ANDREYOLEGOVICH.RU it
AVIASALES travel
BOOKING.COM hotels
HOTELLOOK hotels
TOPBICYCLE.RU bicycles

So that the comma does not disappear, add it between U and L

sed 's/\([^,]*\),\([^,]*\)/\U\1,\L\2/' sites.txt

ANDREYOLEGOVICH.RU, it
AVIASALES, travel
BOOKING.COM, hotels
HOTELLOOK, hotels
TOPBICYCLE.RU, bicycles

What happened: everything up to the first comma was converted to upper case, then sed started looking for the second comma for the second group, did not find it and converted the rest of the line to lower case.

Consider the file mod_sites.txt

AndreyOlegovich.ru, IT, abc, DEF
Aviasales, Travel, ABC, def
Booking.com, Hotels, abc, def
Hotellook, Hotels, ABC, DEF
TopBicycle.ru, Bicycles,,

Apply the same script to it

sed 's/\([^,]*\),\([^,]*\)/\U\1,\L\2/' mod_sites.txt

ANDREYOLEGOVICH.RU, it, abc, DEF
AVIASALES, travel, ABC, def
BOOKING.COM, hotels, abc, def
HOTELLOOK, hotels, ABC, DEF
TOPBICYCLE.RU, bicycles,,

As you can see, after the second comma the case did not change.

To change it you need a third group

sed 's/\([^,]*\),\([^,]*\),\([^,]*\)/\U\1,\L\2,\L\3/' mod_sites.txt

ANDREYOLEGOVICH.RU, it, abc, DEF
AVIASALES, travel, abc, def
BOOKING.COM, hotels, abc, def
HOTELLOOK, hotels, abc, DEF
TOPBICYCLE.RU, bicycles,,

Now everything between the second and the third comma is in lower case.

A slightly more complex variant. This script adds a comma before the last three digits of a number

s/\(^\|[^0-9.]\)\([0-9]\+\)\([0-9]\{3\}\)/\1\2,\3/g

I hope the article was useful to you. If something is unclear, ask in the comments, or in Telegram if they are disabled.

Article author: Andrei Olegovich