0

Problem:

I have a bunch of .sql files that have AS myFieldName aliases. I need to convert all of these to be AS my_field_name without affecting tbl.myFieldName in the first part of each line.

ex:

Before: tbl.myFieldName AS myFieldName,

After: tbl.myFieldName AS my_field_name,

I've used this very simple answer: https://stackoverflow.com/a/28795550/20178 to create a sed command to convert myFieldName to my_field_name, but it does it for the entire line.

I've tried sed 's/*AS ([a-z0-9])([A-Z])/AS \1_\L\2/g' (even though I know this wouldn't work for preserving the first part of the line) but it doesn't seem to match anything at all and so doesn't produce any effect.

How do I add AS as a part of the matching pattern and then match all upppercase letters for replacement?

Noah Goodrich
  • 24,875
  • 14
  • 66
  • 96
  • You need to use `-E` / `-r` option, `sed -E 's/*AS ([a-z0-9])([A-Z])/AS \1_\L\2/g'`. https://stackoverflow.com/a/43549677/3832970 shows that. Why did you remove the option? – Wiktor Stribiżew Jun 25 '20 at 18:16

2 Answers2

0

Using gnu-sed, you may use this:

s='tbl.myFieldName AS myFieldName,'

sed -E ':a;s/(AS .*)([a-z0-9]+)([A-Z])/\1\2_\L\3/g;ta' <<< "$s"
tbl.myFieldName AS my_field_name,

Details:

  • :a: Mark a label a
  • s/(AS .*)([a-z0-9]+)([A-Z])/\1\2_\L\3/g: Substitution of camel case to snak_case of any string that starts AS and space and has 1+ lowercase characters followed by a single uppercase character.
  • ta: If a s/// has done a successful substitution since the last input line was read and since the last t command, then branch to label a
anubhava
  • 761,203
  • 64
  • 569
  • 643
0

This might work for you (GNU sed):

sed 's/AS/&\n/;h;s/[[:upper:]]/_\L&/g;H;g;s/\n.*\n//' file

Divide and conquer. Split the line in two with an introduced newline. Make a copy, amend the whole of the pattern space by inserting an underline and replacing the uppercase letter with its lowercase compliment for all such cases. Append the amended line to its copy and remove everything between the newlines.

Also:

sed -E ':a;s/(AS[^[:upper:]]*)([[:upper:]])/\1_\L\2/;ta' file
potong
  • 55,640
  • 6
  • 51
  • 83