Using awk/sed to parse out multiple strings from a MySQL error
I have a bash script that needs to identify some important sub-strings within a MySQL error generated from a SHOW SLAVE STATUS\G
command run from the terminal. In particular, the line starting with Last_Error: ...
is of significant importance. As as example, if the line read (broken into multiple lines for ease of reading):
Last_Error: Error 'Cannot add or update a child row: a foreign key constraint
fails (`dms/active_sessions`, CONSTRAINT `active_sessions_ibfk_1` FOREIGN KEY
(`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE)'
on query. Default database: 'dms'. Query: 'INSERT INTO active_sessions
(session_id,user_id,lastused,ip) VALUES ('749d9d494c31ab8ee76bf6b6b1127fd2',
'15389','2011-09-27 14:04:59','172.16.11.31')'
Assuming the error string is stored in a variable $LAST_ERROR, I've used the following three variables to store user_id
, th开发者_如何学JAVAe field in the table with the FK constraint, users
, the table that is being referenced by the FK, and id
which is the key in users
that is being referenced:
FIELD=`echo $LAST_ERROR | sed 's/.*FOREIGN KEY [\(\`]*\([0-9a-zA-Z_-]*\)[\`\)]*.*/\1/'`
TABLE=`echo $LAST_ERROR | sed 's/.*REFERENCES \`\([0-9a-zA-Z_-]*\)\`.*/\1/'`
COLUMN=`echo $LAST_ERROR | sed 's/.*REFERENCES \`['$TABLE']*\` [\(\`]*\([0-9a-zA-Z_-]*\)[\`\)]*.*/\1/'`
Are these three variables and their sed commands an acceptable way of finding the values? With those variables defined, I need to parse through the SQL query in the error. The only variable that pertains to this specific case (the rest are being used elsewhere in the script) is $FIELD
. In this case, I need to identify that if the fields specified in the SQL query are:
(session_id,user_id,lastused,ip)
That $FIELD
is the 4th field listed in the SQL query, and it's corresponding value in:
('749d9d494c31ab8ee76bf6b6b1127fd2','15389','2011-09-27 14:04:59','172.16.11.31')
is 15389
. What sed/awk commands can reference the fields listed in the SQL query, and find the corresponding values in the latter part of the query?
Superficially, this sed
script would list the parts you request:
sed 's/.* FOREIGN KEY (\([^)]*\)) REFERENCES \([^(]*\) (\([^)]*\)) .*/(\1) \2 (\3)/'
on the not altogether implausible assumption that you do not use either open or close parentheses in your table and column names. The output is unambiguous and deals with a list of columns referencing another list of columns.
精彩评论