Using sed to change only consecutive repeated letters

前端 未结 2 1698
抹茶落季
抹茶落季 2021-01-24 19:21

Using sed, how to change the letter \'a\' to \'A\' but only if it appears repeated as two or more consecutive letters. Example, from:

galaxy
ear
aardvak
Haaaaaaa         


        
2条回答
  •  滥情空心
    2021-01-24 19:59

    You can do it using groups. If you have this file:

    $ cat a
    galaxy
    ear
    aardvak
    Haaaaaaaaa 
    Ulaanbaatar
    

    You can use this sed command:

    $ sed 's/\(.\)\1\{1,\}/\U&/g' a
    galaxy
    ear
    AArdvak
    HAAAAAAAAA 
    UlAAnbAAtar
    

    What does happen here? If we have a char, "packed" in a group (\(.\)), and this group (\1) repeats itself one or more times (\1\{1,\}), then replace the matched part (&) by its uppercased version (\U&).

提交回复
热议问题