批处理文件,用于在txt文件中的每行的开头和结尾添加字符

时间:2012-04-05 01:19:23

标签: batch-file cmd

嘿伙计们我有一个文本文件,我想知道是否有人有一个批处理文件要添加“到beninning和”,在文本文件的每一行的末尾?

例如我有

1
2
3

我想要

"1",
"2",
"3",

如果有人可以粘贴一个快速的,它会帮助我=)

编辑(从评论到@ mastashake57的帖子):

我在窗户上,如果感觉我要求某人这样做,我的抱怨,这就是我所拥有的。

@echo off 
setlocal 
set addtext=test 
for /f "delims=" %%a in (list.txt) do (echo/|set /p =%%a%addtext% & echo\ & echo) >>new.txt 

但我无法弄清楚如何把逗号放在它认为是我假设的命令的一部分或类似的东西。这只会将文本放在每行的字体中

4 个答案:

答案 0 :(得分:8)

@echo off
setLocal EnableDelayedExpansion
for /f "tokens=* delims= " %%a in (input.txt) do (
set /a N+=1
echo ^"%%a^",>>output.txt
)

-joedf

答案 1 :(得分:4)

在我的脑海里,在Linux中,你可以......

$ for each in `cat filename` ; do echo \"$each\", ; done >> newfilename

"1",
"2",
"3",
"4",
"5",

已编辑 - 因为它适用于Windows,这对我来说很有用:

@echo off
setLocal EnableDelayedExpansion

for /f "tokens=* delims= " %%a in (filename.txt) do (
echo "%%a", >>newfilename.txt
)

答案 2 :(得分:0)

self.module_list

您可以编辑代码:

set "f=PATH\FILE.txt"
call :add_str_beginning_end_each_line "BEGIN_LINE--" "--END_LINE" "%f%"


REM : Adds strings at the beginning and end of each line in file
:add_str_beginning_end_each_line
    set "str_at_begining=%~1"
    set "str_at_end=%~2"
    set "input_file=%~3"

    set "tmp_file=tmp.ini"

    REM : >NUL => copy command is silent
    REM : Make a backup
    copy /Y "!input_file!" "!input_file!.bak" >NUL
    copy /Y "!input_file!" "!tmp_file!" >NUL
    del "!input_file!"

    REM : Add strings at each line
    for /f "delims=" %%a in (!tmp_file!) do (
        >>"!input_file!" echo !str_at_begining!%%a!str_at_end!
    )

    REM : delete backup
    del "!tmp_file!"
    del "!input_file!.bak"

    REM : exiting the function only
    EXIT /B 0

通过删除!str_at_end!仅在行的开头添加str,其中%% a是实际行。

答案 3 :(得分:0)

脚本使用FOR循环计数行数,并使用FOR /LSET /P逐行读取文件:

@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=<CHANGE THIS>"
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

in this answer说明了计算行数的简便方法。
利用SUB字符(0x1A)修剪尾随的换行符,here在DosTips上进行了讨论。如果您不想修剪它们,只需注释掉以;开头的行。