3

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'); 

1 Answer 1

4

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'/"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.