Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 line1
2 line2
etc
like image 504
James Avatar asked May 12 '11 17:05

James


3 Answers

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.

like image 98
Brian Kelly Avatar answered Nov 07 '22 21:11

Brian Kelly


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
)
like image 30
David R Tribble Avatar answered Nov 07 '22 20:11

David R Tribble


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"
like image 1
C.O. Avatar answered Nov 07 '22 21:11

C.O.