如何替换文本中CREATE TABLE IF NOT EXISTS行内表名的特殊字符
替换CREATE TABLE行内的特殊字符为下划线
针对需求——将文本文件中以CREATE TABLE IF NOT EXISTS(不区分大小写)开头的行内,引号中的减号-、空格替换为下划线_,以下是两种实用解决方案:
方案1:使用sed命令(Linux/macOS)
适合终端环境下快速处理,支持原地修改并备份原文件:
sed -i.bak -E '/^[Cc][Rr][Ee][Aa][Tt][Ee] [Tt][Aa][Bb][Ll][Ee] [Ii][Ff] [Nn][Oo][Tt] [Ee][Xx][Ii][Ss][Tt][Ss]/ { s/("[^"]*")/\n\1\n/g; s/[- ]/_/g; s/\n("[^"]*")\n/\1/g }' your_file.txt
-i.bak:原地修改文件,同时生成后缀为.bak的原文件备份- 正则匹配目标行后,先将引号内的内容隔离,再替换特殊字符,最后恢复行结构
方案2:使用Python脚本(跨平台)
适合Windows环境或需要更复杂逻辑的场景,代码清晰易扩展:
import re def process_line(line): # 匹配目标行(不区分大小写) if re.match(r'^CREATE TABLE IF NOT EXISTS', line, re.IGNORECASE): # 替换引号内的特殊字符 def replace_chars(match): content = match.group(1) return f'"{content.replace("-", "_").replace(" ", "_")}"' return re.sub(r'"([^"]+)"', replace_chars, line) return line # 替换文件内容 input_path = "your_file.txt" output_path = "modified_file.txt" with open(input_path, 'r', encoding='utf-8') as infile, open(output_path, 'w', encoding='utf-8') as outfile: for line in infile: outfile.write(process_line(line))
- 遍历文件每一行,仅处理符合条件的行,其他行保持原样
- 可轻松扩展替换其他特殊字符(如添加
replace(".", "_")等)
测试验证
输入示例:
Create table if not exists "abc-xyz" ( col1 int, col2 string ); Create table if not exists "xyz abc" ( col3 int, col2=4 float);
执行后输出:
Create table if not exists "abc_xyz" ( col1 int, col2 string ); Create table if not exists "xyz_abc" ( col3 int, col2=4 float);
内容的提问来源于stack exchange,提问作者Atif Tariq
相关产品推荐
相关产品推荐

