Batch file to add Increment to text list

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
jeff p
Posts: 42
Joined: 28 Jul 2009 10:21

Batch file to add Increment to text list

#1 Post by jeff p » 25 Apr 2013 15:42

I have a text document where I'd like to add an increment to each line of text, while ignoring any blank rows.


ie. from this:

Jack and Jill went up the hill,
to fetch a pail of water.

Jack fell down,
and broke his crown.
And Jill came tumbling after

to this:

001.Jack and Jill went up the hill,
002.to fetch a pail of water.

003.Jack fell down,
004.and broke his crown.
005.And Jill came tumbling after.

If possible, the ability to indicate the directory location /name of the text document to be processed would be great!
Thanks for any help

Jeff

Endoro
Posts: 244
Joined: 27 Mar 2013 01:29
Location: Bozen

Re: Batch file to add Increment to text list

#2 Post by Endoro » 25 Apr 2013 20:51

You can try this:

Code: Select all

@echo off &setlocal
set "folder=d:\myfolder"
pushd "%folder%"

set /a cnt=1000
(for /f "tokens=1*delims=:" %%i in ('^<"input.txt" findstr /n "^"') do (
    set "line=%%j"
    if defined line (
        set /a cnt+=1
        setlocal enabledelayedexpansion
        set "pre=!cnt:~-3!"
        echo(!pre!.!line!
        endlocal
    ) else echo(
))>"output.txt"
popd

foxidrive
Expert
Posts: 6031
Joined: 10 Feb 2012 02:20

Re: Batch file to add Increment to text list

#3 Post by foxidrive » 25 Apr 2013 22:29

Just be aware that the above code will corrupt a file that has any : characters at the start of a line.

Endoro
Posts: 244
Joined: 27 Mar 2013 01:29
Location: Bozen

Re: Batch file to add Increment to text list

#4 Post by Endoro » 25 Apr 2013 23:47

Yes, you are completely right :mrgreen:

But I was able to fix it:

Code: Select all

@echo off &setlocal
set "folder=d:\myfolder"
pushd "%folder%"

set /a cnt=1001
(for /f "delims=" %%i in ('^<"input.txt" findstr /n "^"') do (
    set "line=%%i"
    setlocal enabledelayedexpansion
   set "line=!line:*:=!"
    if defined line (
        set "pre=!cnt:~-3!"
        echo(!pre!.!line!
      endlocal
      set /a cnt+=1
    ) else (
      echo(
       endlocal
   )
))>"output.txt"
popd

jeff p
Posts: 42
Joined: 28 Jul 2009 10:21

Re: Batch file to add Increment to text list

#5 Post by jeff p » 26 Apr 2013 00:16

Thanks for the script, Endoro!

But I'm unable to get this to work.
I've set up a simple text document containing a single sentence.
I've included my path directory and text file name to the code.
When I run the bat file, the command prompt window opens but hangs there.
An output.txt file is created but it is empty.


Any ideas?

Thanks

jeff p
Posts: 42
Joined: 28 Jul 2009 10:21

Re: Batch file to add Increment to text list

#6 Post by jeff p » 26 Apr 2013 00:22

Never mind. i needed to add an Enter at the end of my file.

Many thanks for the help.

Works Great!!

Post Reply