bat 正则换行 如何撰写?-灵析社区

HAO起起

bat批处理的代码如下 @echo off setlocal enabledelayedexpansion :: 设置文件夹路径 set "folderPath=D:\txt\" :: 遍历文件夹里的所有 txt 文件 for %%F in (%folderPath%\*.txt) do ( set "inputFile=%%F" set "outputFile=%%F_temp.txt" :: 第一步:替换特定字符为空 powershell -Command "(Get-Content '!inputFile!') -replace '[「」【】]', '' | Set-Content '!outputFile!'" :: 第二步:用正则表达式限制每行的字符数并添加新行 powershell -Command "(Get-Content '!outputFile!') -replace '(.{6,18}[,。:!?]|.{16})', '$1`n' | Set-Content '!outputFile!'" :: 第三步:替换特定字符为空 powershell -Command "(Get-Content '!outputFile!') -replace '[,。!]', '' | Set-Content '!outputFile!'" :: 第四步:移除空行 powershell -Command "(Get-Content '!outputFile!') | ? {$_ -ne ''} | Set-Content '!outputFile!'" :: 替换原文件 move /Y "!outputFile!" "!inputFile!" echo 文件 %%F 处理完成! ) echo 所有文件处理完成! pause 其中第二步中的用正则表达式限制每行的字符数并添加新行 powershell -Command "(Get-Content '!outputFile!') -replace '(.{6,18}[,。:!?]|.{16})', '$1`n' | Set-Content '!outputFile!'" 可以实现正则定位,但是无法实现换行,要如何修改,\n \r 设置了无效? $1 部分正常识别,但是一到换行就直接输出 n 并不能换行

阅读量:408

点赞量:19

问AI
用python怎么样 replace.py import re import os import sys def handle(folder_path): if not os.path.exists(folder_path): print("{} 为无效路径".format(folder_path)) return # 按顺序执行正则替换,可自行添加正则 pattern_replacements = [[r'[「」【】]',''], [r'(.{6,18}[,。:!?]|.{16})',r'\1\r\n'], [r'[,。!]',''], [r'[\r\n]+','\n']] data = '' for file in os.listdir(folder_path): file_path = os.path.join(folder_path,file) if not os.path.isdir(file_path) and file_path.endswith('.txt'): with open(file_path,'r',encoding='utf-8') as fr: data = fr.read() for pattern,replacement in pattern_replacements: data = re.sub(pattern,replacement,data) with open(file_path,'w',encoding='utf-8') as fw: fw.write(data) print("{} 处理完成".format(file)) print("全部处理完成") if __name__ == "__main__": folder_path = r"d:\txt" if len(sys.argv) > 1: folder_path = sys.argv[1] handle(folder_path) start.bat @echo off set "folderPath=D:\txt\" REM 检查系统环境变量中是否存在Python路径 where python > nul 2>&1 if %errorlevel% equ 0 ( REM Python路径已添加到系统环境变量中 set "python_path=python" ) else ( REM Python路径未添加到系统环境变量中,需手动设置Python路径,以下为测试路径 set "python_path=D:\Env\Python\Python38\python.exe" ) %python_path% replace.py %folderPath% || pause pause 把start.bat和replace.py放到同一个文件夹,配置下python路径就可以执行批处理文件了