0

I want to replace kAbcdedf with abcdef in a file. I try to use the sed command. Some suggestions said, if I input this command

echo 'abc'|sed 's/^../\u&/'

the result will be

Abc

but on macOS (using zsh), the result is

uabc

Does anyone know the correct way to toggle cases with the sed command?

How can I search kAbcd and then replace that string with abcd, i.e., remove k and uppercase the next letter after k?

Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
whitekevin
  • 311
  • 3
  • 15

1 Answers1

2
$ # with GNU sed
$ echo 'kAbcd' | sed -E 's/k(.)/\l\1/'
abcd

$ # with perl if GNU sed is not available
$ echo 'kAbcd' | perl -pe 's/k(.)/\l$1/'
abcd
  • \l will lowercase the first character of given argument
  • use g modifier to replace all such occurrences in a line

As mentioned by Wiktor Stribiżew in comments, see also: How to use GNU sed on Mac OS X

Sundeep
  • 23,246
  • 2
  • 28
  • 103
  • By the way, if I want with GNU sed to covert abcd.kAbcd to abcd.abcd, how should I write command? thanks~ – whitekevin May 09 '18 at 07:03
  • the same command as mentioned in the answer.. by default, matching is done anywhere in the line.. you can change that using anchors, word boundaries and other things.. see https://www.gnu.org/software/sed/manual/sed.html#sed-regular-expressions for details – Sundeep May 09 '18 at 07:51