I would like to remove a column name value pair from one INSERT statement and move it into another INSERT statement. I have about a hundred seperate files that have this sort of format (although the format may vary slightly from file to file, for instance some users may have put the entire INSERT statement on one line).
INPUT
INSERT INTO table1 (
col1,
col2
)
VALUES (
foo,
bar
);
INSERT INTO table2 (
col3,
col4_move_this_one,
col5
)
VALUES (
john,
doe_move_this_value,
doe
);
OUTPUT
INSERT INTO table1 (
col1,
col4_move_this_one,
col2
)
VALUES (
foo,
doe_move_this_value,
bar
);
INSERT INTO table2 (
col3,
col5
)
VALUES (
john,
doe
);
In general with the above format I was thinking I could use sed and cat in a script to find line numbers of each line to be moved and then move it, something like this.
for file in *; do
line_number=$(cat -n ${file} | sed some_statement | awk to_get_line_number)
# etc...
done
...but maybe you guys can recommend a more clever way that would work also if the INSERT statement is on one line.
A GAWK version that relies on
gensub
's backreference feature and heavily on regex.This solution assumes that variables to copy are the second variables in the second
INSERT
after keywordsINSERT
andVALUES
and that they are added to those same places in the firstINSERT
. Solution is space and\n
friendly but doesn't support\t
, easily fixed I assume.With GNU awk for true multi-dimensional arrays, 3rd arg to match(), multi-char RS and \s/\S syntactic sugar:
.