Batch file to add characters to beginning and end of each line in txt file

后端 未结 4 1362
小鲜肉
小鲜肉 2020-12-06 06:50

I have a text file, I was wondering anyone have a batch file to add \" to the beninning and \", at the end of each line in a text file?

For example I have



        
4条回答
  •  旧时难觅i
    2020-12-06 07:28

    The script uses a FOR loop count the # of lines, and FOR /L along with SET /P to read the file line-by-line:

    @echo off
    SETLOCAL EnableDelayedExpansion
    
    ::Initialize SUB character (0x1A)
    >nul copy nul sub.tmp /a
    for /F %%S in (sub.tmp) do set "sub=%%S" SUB CHARACTER
    
    ::Variables
    ;set "lines=-1" Exclude LAST line
    set "in="
    set "out=text.txt"
    
    ::Count lines
    FOR /F tokens^=*^ delims^=^ eol^= %%L in (
    '2^>nul findstr /N "^" "%in%"'
    ) do set /a "lines+=1"
    
    ::Read file using SET /P
    >newline.tmp <"!in!" (
      for /L %%a in (1 1 %lines%) do (
        set "x=" For EMPTY lines
        set /p "x="
        echo("!x!",
      )
        ;set "x="
        ;echo("!x!",!sub!
    )
    
    ::Trim trailing newline appended by ECHO
    ;copy newline.tmp /a "!out!" /b
    ;del sub.tmp newline.tmp
    

    The foolproof way of counting the number of lines is explained in this answer.
    Takes advantage of the SUB character (0x1A) to trim trailing newlines, discussed here on DosTips. If you don't want to trim them, just comment out the lines that start with ;.

提交回复
热议问题