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
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&
).
EDIT
You can do this with:
sed 's/a\(a\+\)/A\U\1/;s/b\(b\+\)/B\U\1/;s/c\(c\+\)/C\U\1/;s/d\(d\+\)/D\U\1/;s/e\(e\+\)/E\U\1/;s/f\(f\+\)/F\U\1/;s/g\(g\+\)/G\U\1/;s/h\(h\+\)/H\U\1/;s/i\(i\+\)/I\U\1/;s/j\(j\+\)/J\U\1/;s/k\(k\+\)/K\U\1/;s/l\(l\+\)/L\U\1/;s/m\(m\+\)/M\U\1/;s/n\(n\+\)/N\U\1/;s/o\(o\+\)/O\U\1/;s/p\(p\+\)/P\U\1/;s/q\(q\+\)/Q\U\1/;s/r\(r\+\)/R\U\1/;s/s\(s\+\)/S\U\1/;s/t\(t\+\)/T\U\1/;s/u\(u\+\)/U\U\1/;s/v\(v\+\)/V\U\1/;s/w\(w\+\)/W\U\1/;s/x\(x\+\)/X\U\1/;s/y\(y\+\)/Y\U\1/;s/z\(z\+\)/Z\U\1/'
(Thanks to shelter)
Or with a pipe of sed:
function capitalize_consecutives () {
sed 's/a\(a\+\)/A\U\1/' |
sed 's/b\(b\+\)/B\U\1/' |
sed 's/c\(c\+\)/C\U\1/' |
sed 's/d\(d\+\)/D\U\1/' |
sed 's/e\(e\+\)/E\U\1/' |
sed 's/f\(f\+\)/F\U\1/' |
sed 's/g\(g\+\)/G\U\1/' |
sed 's/h\(h\+\)/H\U\1/' |
sed 's/i\(i\+\)/I\U\1/' |
sed 's/j\(j\+\)/J\U\1/' |
sed 's/k\(k\+\)/K\U\1/' |
sed 's/l\(l\+\)/L\U\1/' |
sed 's/m\(m\+\)/M\U\1/' |
sed 's/n\(n\+\)/N\U\1/' |
sed 's/o\(o\+\)/O\U\1/' |
sed 's/p\(p\+\)/P\U\1/' |
sed 's/q\(q\+\)/Q\U\1/' |
sed 's/r\(r\+\)/R\U\1/' |
sed 's/s\(s\+\)/S\U\1/' |
sed 's/t\(t\+\)/T\U\1/' |
sed 's/u\(u\+\)/U\U\1/' |
sed 's/v\(v\+\)/V\U\1/' |
sed 's/w\(w\+\)/W\U\1/' |
sed 's/x\(x\+\)/X\U\1/' |
sed 's/y\(y\+\)/Y\U\1/' |
sed 's/z\(z\+\)/Z\U\1/'
}
Then let it parses your file:
capitalize_consecutives < myfile
\U
is to UPPERCASE the occurence. I guess this is only for GNU sed.