我有一个包含以下内容的文件:
$ 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');
我想更换第一次出现与。locale = 'fr-FR'
locale = 'fr_FR.utf8'
替换后文件应具有以下内容:
$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
使用 GNU sed,您可以使用特殊的双地址形式0,/regexp/
将替换命令限制在直到第一个实例的范围内:
$ 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');
LHS 上的空模式导致s/pattern/replacement
它重新使用地址中的前一个模式。
当然,如果你知道你只想在第一行进行替换,你可以使用更简单的"1s/'fr-FR'/'fr_FR.utf8'/"