批处理脚本中的正则表达式

时间:2021-05-20 12:41:15

标签: regex batch-file

我有 file.txt 格式的值:

text1
text2
text3

任何人都有想法在脚本中打开这样的文件并将其修改为

'text1','text2','text3'

到目前为止,我已经在记事本++中手动完成了,但我宁愿把它放在一些脚本中,只是不知道如何:

first step: 
find what: ^|$  
replace with: '

second step:
find what: [\r\n]+
replace with: ,

1 个答案:

答案 0 :(得分:2)

您想将包含行的文件转换为单行文件,其中单行(原始)行用单引号括起来并用逗号分隔。

效率不高,但简单明了:

@echo off
set "infile=input.txt"
set "outfile=output.txt"
del "%outfile%" 2>nul
for /f "usebackq delims=" %%a in ("%infile%") do (
  if not exist "%outfile%" (
    <nul set /p "='%%a'" > "%outfile%
  ) else (
    <nul set /p "=,'%%a'" >>"%outfile%"
  )
)
>>"%outfile%" echo(
type "%outfile%"

一行一行,如果是第一行,写引用的值,否则写一个逗号加上引用的值,都用<nul set /p技巧来写而不换行。