本文目录导读:

下面我为您提供几种批量排序导入语句的脚本方案,涵盖常见场景:
Python脚本 - 排序SQL文件中的INSERT语句
#!/usr/bin/env python3
"""
批量排序SQL导入语句脚本
功能:读取SQL文件,按指定列排序INSERT语句
"""
import re
import sys
import argparse
def parse_sql_inserts(file_path):
"""解析SQL文件中的INSERT语句"""
with open(file_path, 'r', encoding='utf-8') as f:
content = f.read()
# 匹配INSERT INTO ... VALUES (...)
insert_pattern = re.compile(
r'INSERT\s+INTO\s+`?\w+`?\s*\(([^)]*)\)\s*VALUES\s*\((.*?)\);',
re.IGNORECASE | re.DOTALL
)
inserts = []
columns = None
for match in insert_pattern.finditer(content):
cols = match.group(1).strip()
values = match.group(2).strip()
if columns is None:
columns = cols
inserts.append(values)
return columns, inserts
def sort_inserts(inserts, sort_column_index, reverse=False):
"""按指定列排序INSERT数据"""
def get_sort_key(values_str):
# 分割VALUES中的值
values = values_str.split(',')
# 去除引号和空格
target_value = values[sort_column_index].strip().strip("'\"")
# 尝试转换为数字排序
try:
return (0, float(target_value))
except ValueError:
return (1, target_value)
return sorted(inserts, key=get_sort_key, reverse=reverse)
def generate_sql(table_name, columns, sorted_inserts):
"""生成排序后的SQL语句"""
lines = [f"INSERT INTO {table_name} ({columns}) VALUES"]
for i, values in enumerate(sorted_inserts):
suffix = ',' if i < len(sorted_inserts) - 1 else ';'
lines.append(f" ({values}){suffix}")
return '\n'.join(lines)
def main():
parser = argparse.ArgumentParser(description='批量排序SQL导入语句')
parser.add_argument('input_file', help='输入SQL文件路径')
parser.add_argument('output_file', help='输出SQL文件路径')
parser.add_argument('--table', '-t', default='users', help='表名')
parser.add_argument('--column', '-c', type=int, default=0, help='排序依据列索引(从0开始)')
parser.add_argument('--reverse', '-r', action='store_true', help='降序排列')
args = parser.parse_args()
try:
columns, inserts = parse_sql_inserts(args.input_file)
sorted_inserts = sort_inserts(inserts, args.column, args.reverse)
result = generate_sql(args.table, columns, sorted_inserts)
with open(args.output_file, 'w', encoding='utf-8') as f:
f.write(result)
print(f"✓ 排序完成!共处理 {len(inserts)} 条记录")
print(f" 输出文件: {args.output_file}")
except Exception as e:
print(f"✗ 错误: {e}", file=sys.stderr)
sys.exit(1)
if __name__ == '__main__':
main()
使用示例:
# 基本用法 python sort_sql.py input.sql output.sql # 按第2列(年龄)排序 python sort_sql.py input.sql output.sql -c 1 # 降序排列 python sort_sql.py input.sql output.sql -r
Shell脚本 - 使用sort命令
#!/bin/bash
# sort_inserts.sh - 使用Linux/Unix命令排序SQL插入语句
INPUT_FILE=$1
OUTPUT_FILE=$2
SORT_COLUMN=${3:-1} # 默认按第1列排序
if [ -z "$INPUT_FILE" ] || [ -z "$OUTPUT_FILE" ]; then
echo "用法: $0 <输入文件> <输出文件> [排序列号]"
exit 1
fi
# 提取所有INSERT语句并排序
awk '
BEGIN { in_values = 0; }
/INSERT INTO/ {
if (match($0, /\((.*)\);/, vals)) {
print vals[1]
}
next
}
' "$INPUT_FILE" | sort -t',' -k${SORT_COLUMN} -n > /tmp/values_sorted.txt
# 重新生成INSERT语句
echo "INSERT INTO table_name (column1, column2, column3) VALUES" > "$OUTPUT_FILE"
while IFS= read -r line; do
echo " ($line),"
done < /tmp/values_sorted.txt | sed '$s/,$/;/' >> "$OUTPUT_FILE"
echo "排序完成!输出文件: $OUTPUT_FILE"
使用方法:
chmod +x sort_inserts.sh ./sort_inserts.sh input.sql output.sql 2
通用Python脚本 - 处理CSV/TXT导入
#!/usr/bin/env python3
"""
通用批量排序导入脚本 - 支持多种格式
"""
import csv
import sys
import argparse
def sort_and_export(input_file, output_file, sort_column, delimiter=',',
header=True, reverse=False, file_type='csv'):
"""排序并导出数据"""
with open(input_file, 'r', encoding='utf-8') as f:
if file_type == 'csv':
reader = csv.reader(f)
data = list(reader)
elif file_type == 'tsv':
reader = csv.reader(f, delimiter='\t')
data = list(reader)
else:
data = [line.strip().split(delimiter) for line in f if line.strip()]
# 处理表头
if header and data:
headers = data[0]
data = data[1:]
else:
headers = None
# 排序
try:
data.sort(key=lambda x: float(x[sort_column]) if x[sort_column].replace('.','',1).isdigit()
else x[sort_column],
reverse=reverse)
except (IndexError, ValueError) as e:
print(f"排序错误: {e}", file=sys.stderr)
sys.exit(1)
# 写入输出
with open(output_file, 'w', encoding='utf-8', newline='') as f:
writer = csv.writer(f)
if headers:
writer.writerow(headers)
writer.writerows(data)
return len(data)
def main():
parser = argparse.ArgumentParser(description='批量排序导入数据')
parser.add_argument('input', help='输入文件')
parser.add_argument('output', help='输出文件')
parser.add_argument('--column', '-c', type=int, default=0, help='排序列(从0开始)')
parser.add_argument('--delimiter', '-d', default=',', help='分隔符')
parser.add_argument('--no-header', action='store_true', help='无表头')
parser.add_argument('--reverse', '-r', action='store_true', help='降序')
parser.add_argument('--type', '-t', choices=['csv', 'tsv', 'custom'],
default='csv', help='文件类型')
args = parser.parse_args()
count = sort_and_export(
args.input,
args.output,
args.column,
args.delimiter,
not args.no_header,
args.reverse,
args.type
)
print(f"✅ 排序完成!共处理 {count} 行数据")
print(f" 输出文件: {args.output}")
if __name__ == '__main__':
main()
使用建议
- 对于复杂SQL文件:推荐使用第一个Python脚本,它能正确处理嵌套引号和复杂值
- 对于大型文件:使用Shell脚本效率最高
- 对于CSV数据:使用通用脚本,灵活支持多种格式
示例用法
# 1. SQL文件排序 python sort_sql.py data.sql sorted_data.sql --table users --column 2 # 2. CSV文件排序 python sort_generic.py data.csv sorted.csv --column 1 --reverse # 3. 管道方式 cat input.sql | python sort_sql.py /dev/stdin output.sql
这些脚本都能很好地处理批量排序导入语句的需求,根据您的具体使用场景选择合适的脚本即可。
版权声明:NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播