Selectively search and replace specific strings using regex

I have a file containing many SQL statements, for example:

CREATE TABLE "USER" (
    "ID" INTEGER PRIMARY KEY,
    "NAME" CHARACTER VARYING(50) NOT NULL,
    "AGE" INTEGER NOT NULL
);

COPY "USER" (id, name, age) FROM stdin;
1   Skywalker   19
2   Kenobi      57

I want the column names in the statements to COPYbe uppercase and specified:

COPY "USER" ("ID", "NAME", "AGE") FROM stdin;

Using sed, I found the following regexp:

sed -r 's/([( ])(\w+)([,)])/\1"\U\2\E"\3/g'

It replaces the column names, but it is not selective enough and replaces other words in the file:

~/test]$sed -r 's/([( ])(\w+)([,)])/\1"\U\2\E"\3/g' star_wars_example
CREATE TABLE "USER" (
  "ID" INTEGER PRIMARY "KEY",
  "NAME" CHARACTER VARYING("50")NOT "NULL",
  "AGE" INTEGER NOT NULL
);

COPY "USER" ("ID", "NAME", "AGE") FROM stdin;
1   Skywalker   19
2   Kenobi      57

To avoid this problem, I want sed to apply my regex to lines starting with COPYand ending with FROM stdin;.

I looked in lookahead / lookbehind, but they are not supported in sed. They seem to be supported in super-sed, but I'm currently using Cygwin (Windows is required here ...) and it doesn't seem to be available in the package list.

sed ?

grep sed, .

- ?

, Cygwin . , -sed cygwin, ,

+3
1

sed, , ( ) =)

Try

sed -r '/^COPY /{ s/([( ])(\w+)([,)])/\1"\U\2\E"\3/g }'

, , COPY.

- . , .

+2

Source: https://habr.com/ru/post/1747338/


All Articles