9

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

例如我有

1
2
3

而且我要

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

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

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

我在 Windows 上,如果我觉得我是在要求某人做这件事,我很抱歉,这就是我所拥有的。

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

但我不知道如何放置逗号,因为它认为它是我假设的命令的一部分或类似的东西。这只会将文本放置在每行的字体中。

4

4 回答 4

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

-乔德夫

于 2012-04-05T01:41:42.397 回答
5

在我的脑海中,在 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
)
于 2012-04-05T01:28:44.543 回答
0
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

您可以编辑代码:

    "!input_file!" echo !str_at_begining!%%a!str_at_end!

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

于 2020-04-25T08:52:31.473 回答
0

该脚本使用FOR循环计数行数,并FOR /L逐行SET /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

这个答案解释了计算行数的万无一失的方法。
利用SUB字符 (0x1A) 来修剪尾随换行符,在DosTips上进行了讨论。如果您不想修剪它们,只需注释掉以 . 开头的行;

于 2020-04-25T10:06:58.063 回答