Search code examples
batch-filefindstr

Batch Insert the line number in each line


I have a little problem and can not get on right now. I would like to batch import a .txt file and output this with line numbers to another .txt. For example, the test.txt file looks like this:

hello
how 
are 
you

The result should be the file test2.txt and look like this:

1: hello
2: how
3: are
4: you

I have tried the following batch but unfortunately I only get an empty file as output:

@echo off
setlocal enabledelayedexpansion
findstr / n; test.txt >test2.txt

Does anyone have an idea? Thanks in advance!


Solution

  • This version will do write from test.txt to test2.txt:

    @echo off
    setlocal enabledelayedexpansion
    
    set "myfile=test.txt"
    set "outputfile=test2.txt"
    
    for /f "tokens=*" %%a in ('type "%myfile%" ^| find /v /n "" ^& break ^> "%myfile%"') do (
         set "str=%%a
         set "str=!str:]=: !"
         set "str=!str:[=!"
         >>%outputfile% echo(!str!
      )
    

    This version will write back to the original file, test.txt and write back to test.txt, thus overwriting it:

    @echo off
    setlocal enabledelayedexpansion
    
    set "myfile=test.txt"
    
    for /f "tokens=*" %%a in ('type "%myfile%" ^| find /v /n "" ^& break ^> "%myfile%"') do (
         set "str=%%a
         set "str=!str:]=: !"
         set "str=!str:[=!"
         >>%myfile% echo(!str!
      )
    

    Which will do what you want:

    1: hello
    2: how 
    3: are 
    4: you
    

    Note, this will also number \n in other words new empty lines. So for instance, if you have:

    hello
    
    how 
    are 
    you
    

    It will result in:

    1: hello
    2:
    3: how 
    4: are 
    5: you