Score:3

Replace a text within single quotes with another string using sed(just a first occurrence of regex)

ph flag

I have a file with the following content:

$ cat file.txt
CREATE COLLATION public.collation123 (provider = libc, locale = 'fr-FR');  
CREATE COLLATION public.collation_1 (provider = libc, locale = 'bas');  
CREATE COLLATION public.collation_test (provider = libc, locale = 'fr-FR');   

I want to replace the first occurrence of locale = 'fr-FR' with locale = 'fr_FR.utf8'.

After replacing, the file should have the following content:

$cat file.txt
CREATE COLLATION public.collation123 (provider = libc, locale = 'fr_FR.utf8');  
CREATE COLLATION public.collation_1 (provider = libc, locale = 'bas');  
CREATE COLLATION public.collation_test (provider = libc, locale = 'fr-FR'); 
Score:4
hr flag

With GNU sed, you can use the special two-address form 0,/regexp/ to restrict a substitution command to a range up to and including the first instance:

$ cat file.txt
CREATE COLLATION public.collation123 (provider = libc, locale = 'fr-FR');
CREATE COLLATION public.collation_1 (provider = libc, locale = 'bas');
CREATE COLLATION public.collation_test (provider = libc, locale = 'fr-FR');

$ sed "0,/'fr-FR'/s//'fr_FR.utf8'/" file.txt
CREATE COLLATION public.collation123 (provider = libc, locale = 'fr_FR.utf8');
CREATE COLLATION public.collation_1 (provider = libc, locale = 'bas');
CREATE COLLATION public.collation_test (provider = libc, locale = 'fr-FR');

The empty pattern on the LHS of the s/pattern/replacement causes it to re-use the previous pattern from the address.

Of course, if you know that you only want to make the substitution in the first line, you can use the simpler "1s/'fr-FR'/'fr_FR.utf8'/"

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.