如何用Shell脚本统一mysqldump输出中同缩进列定义的顺序
解决mysqldump列顺序随机问题的Shell脚本
可以使用GNU awk编写脚本,实现每个表中id列固定在首位,其余列按名称排序,同时保持表的顺序和其他结构(如主键、引擎配置)不变。执行命令如下:
mysqldump [你的mysqldump参数] | awk ' BEGIN { in_table=0; } /^create TABLE/ { if (in_table) { print_sorted_table(); } in_table=1; table_header=$0; id_line=""; delete columns; other_lines=""; next; } /^ `id`/ { id_line=$0; next; } /^ `column_/ { col_name=substr($2, 2, length($2)-2); # 提取列名(去掉反引号) columns[col_name]=$0; next; } /^ PRIMARY KEY/ || /^) ENGINE=InnoDB;/ { other_lines=other_lines $0 "\n"; if (/^) ENGINE=InnoDB;/) { print_sorted_table(); in_table=0; } next; } function print_sorted_table() { print table_header; print id_line; # 按列名字典序排序输出其他列 PROCINFO["sorted_in"]="@ind_str_asc"; for (col in columns) { print columns[col]; } printf "%s", other_lines; } ' > sorted_dump.sql
脚本说明
- 表结构识别:通过
create TABLE标记表定义开始,) ENGINE=InnoDB;标记表定义结束 - 列处理逻辑:
- 单独保留
id列的行,确保它始终是第一个列定义 - 收集所有非
id列,以列名为键存储,后续按字典序排序输出
- 单独保留
- 结构保留:主键定义、引擎配置等非列定义行,直接按原顺序保留输出
使用示例
将mysqldump命令输出通过管道传入上述awk脚本,即可得到列顺序统一的备份文件:
mysqldump -u root -p --no-data my_database | awk '[上述脚本内容]' > sorted_schema.sql
内容的提问来源于stack exchange,提问作者steven_noble
相关产品推荐
相关产品推荐

