如何将行号从批处理文件添加到文本文件 (Windows)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5981962/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 16:50:27  来源:igfitidea点击:

How to add line numbers to a text file from a batch file (Windows)

windowsbatch-file

提问by James

How would I be able to add line numbers to a text file from a batch file / command prompt?

我如何能够从批处理文件/命令提示符向文本文件添加行号?

e.g.

例如

1 line1
2 line2
etc

采纳答案by Brian Kelly

Here you go:

干得好:

@echo off
FOR /L %%G IN (1, 1, 100) DO (
     echo %%G line%%G
)

This will probably only work in a batch file and not on the command line.

这可能只适用于批处理文件,而不适用于命令行。

For more info, see this page.

有关详细信息,请参阅此页面

If you want to loop over an existing file and add numbers to it, you'd have to process the file with a for /F loopinstead, and within each loop iteration use a statement like set /a counter+=1to increment your counter. Then spit out each line to a new file and finally replace the old file with the new one.

如果要循环遍历现有文件并向其添加数字,则必须使用for /F 循环来处理文件,并且在每次循环迭代中使用类似set /a counter+=1增加计数器的语句。然后将每一行吐出到一个新文件中,最后用新文件替换旧文件。

回答by David R Tribble

The closest I could get was this, which does not work:

我能得到的最接近的是这个,它不起作用:

@echo off

set file=%1     
set x=1

for /f "delims=|" %%i in (%file%) do (
  echo %x% %%i
  set /a x=%x%+1
)

The setinside the forloop does not work (because we're in crappy DOS).

set内部for循环不工作(因为我们是在蹩脚的DOS)。

Replacing the setwith a callto another batch file to do the increment and setting of xdoes not work, either.

seta替换call为另一个批处理文件来执行增量和设置x也不起作用。

Addendum

附录

Okay, adding the fixes suggested by @indiv, we get this (which does seem to work):

好的,添加@indiv 建议的修复程序,我们得到了这个(似乎确实有效):

@echo off

set file=%1     
set x=1
setlocal EnableDelayedExpansion

for /f "delims=|" %%i in (%file%) do (
  echo !x! %%i
  set /a x=!x!+1
)

回答by C.O.

All way too complicated, let's necromance this. For Windows XP and later (we need findstr) the following is all it takes on the command line or in batch to add line numbers to an input file as the OP wanted...

太复杂了,让我们对此进行死灵。对于 Windows XP 及更高版本(我们需要 findstr),以下是根据 OP 的需要在命令行或批处理中将行号添加到输入文件所需的全部内容...

type "in.txt"|findstr/n ^^ > "out.txt"