开发者

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

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

e.g.

1 l开发者_开发知识库ine1
2 line2
etc


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 loop instead, and within each loop iteration use a statement like set /a counter+=1 to increment your counter. Then spit out each line to a new file and finally replace the old file with the new one.


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 set inside the for loop does not work (because we're in crappy DOS).

Replacing the set with a call to another batch file to do the increment and setting of x does not work, either.

Addendum

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

@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
)


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...

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜