如何通过Batch脚本或PowerShell批量为文本文件列添加双引号
需求说明
现有文本文件格式如下(包含表头、数据行及空列,以竖线|分隔):
KML|ID|CODE|----------and so on //Header abc|123|hasc|ikjh|0.9888|udee|*|0.00|gsgs|-367.99||||||9.18282823334| //Body end of file
需要为每一列的非空内容添加双引号,空列保持原样,最终输出效果如下:
"abc"|"123"|"hasc"|"ikjh"|"0.9888"|"udee"|"*"|"0.00"|"gsgs"|"-367.99"||||||"9.18282823334"|
PowerShell 实现脚本
# 替换为你的源文件和输出文件路径 $inputPath = "input.txt" $outputPath = "output.txt" Get-Content $inputPath | ForEach-Object { # 跳过表头、空行和注释行(不需要处理的行原样输出) if ($_ -match '^//' -or [string]::IsNullOrWhiteSpace($_) -or $_ -match 'KML\|ID\|CODE') { $_ } else { # 按|分割列,保留所有空列 $columns = $_ -split '\|', 0 $processedColumns = $columns | ForEach-Object { # 非空列加双引号,空列保持原样 if (-not [string]::IsNullOrWhiteSpace($_)) { "`"$_`"" } else { $_ } } # 重新拼接成竖线分隔的行 $processedColumns -join '|' } } | Set-Content $outputPath
补充说明
- 如果表头也需要添加引号,删除判断条件中的
-or $_ -match 'KML\|ID\|CODE'即可 -split '\|', 0中的0参数确保保留末尾的空列结构,避免分割后丢失最后一个|后的空内容
Batch 实现脚本
@echo off setlocal enabledelayedexpansion :: 替换为实际文件路径 set "inputFile=input.txt" set "outputFile=output.txt" :: 清空输出文件 type nul > "%outputFile%" :: 逐行读取源文件 for /f "usebackq delims=" %%a in ("%inputFile%") do ( set "currentLine=%%a" :: 跳过表头、空行和注释行,原样输出 echo !currentLine! | findstr /r "^//" >nul && ( echo !currentLine! >> "%outputFile%" goto nextLine ) if "!currentLine!"=="" ( echo. >> "%outputFile%" goto nextLine ) echo !currentLine! | findstr /r "KML\|ID\|CODE" >nul && ( echo !currentLine! >> "%outputFile%" goto nextLine ) :: 处理数据行:分割列并为非空列加引号 set "processedLine=" :splitLoop for /f "tokens=1* delims=|" %%b in ("!currentLine!") do ( set "column=%%b" if not "!column!"=="" ( set "processedLine=!processedLine!""!column!""|" ) else ( set "processedLine=!processedLine!|" ) set "currentLine=%%c" if not "!currentLine!"=="" goto splitLoop ) :: 输出处理后的行(保留末尾的竖线结构) echo !processedLine!>> "%outputFile%" :nextLine ) endlocal echo 处理完成,结果已保存到%outputFile%
补充说明
- 若需要处理表头,删除对应的
findstr /r "KML\|ID\|CODE"判断块即可 - Batch脚本通过循环分割列的方式,确保空列和末尾的竖线结构完整保留
内容的提问来源于stack exchange,提问作者Karanraj Kasat
相关产品推荐
相关产品推荐

