0

What's a simple way to convert (a stream of space-separated) words in camelCase to snake_case, using the command shell (e.g. bash)?

This is a simpler case relative to an earlier question which I've deleted.

anubhava
  • 761,203
  • 64
  • 569
  • 643
einpoklum
  • 118,144
  • 57
  • 340
  • 684

1 Answers1

2

With GNU sed you can easily convert to lowercase and prefix with underscore:

$ echo camelCase andAnother | sed 's/[A-Z]/_\l&/g'
camel_case and_another
oguz ismail
  • 1
  • 16
  • 47
  • 69
fancyPants
  • 50,732
  • 33
  • 89
  • 96
  • That's what I get for simplifying my question too much :-( Fair enough. Initially I also wanted to handle thisKINDOfIdentifiers. – einpoklum Aug 11 '20 at 10:21
  • You can make the `\l`sinto ae`\L` to lowercase all of them. The pattern would have to be more complicated, though; simply adding a `+` after the `[A-Z]` would take one too many characters. You’d need lookaheads to really handle it, probably, and I don’t knoweif POSIX EREs supprt those. – Daniel H Aug 11 '20 at 10:47
  • After playing around with it, I think you need a more complicated `sed` command: `sed -r -e 's/^([A-Z]+)([A-Z])/\L\1\E\2/' -e 's/^[A-Z]/\l&/' -e 's/[A-Z]+$/_\L&/' -e 's/([A-Z]+)([A-Z])/_\L\1\E\2/g' -e 's/[A-Z]/_\l&/g'` will do it, for *line*-separated words instead of *space-separated* ones. That also handles `PascalCase` instead of `camelCase`. – Daniel H Aug 11 '20 at 11:21
  • (If you want I can make a full answer explaining that, but not now) – Daniel H Aug 11 '20 at 11:23