Batch Script to extract parts of a string

May 28, 2010 at 08:32:14
Specs: Windows XP

I need a batch script that will read in a file and extract from it just a section of the a string of text. Example below
from that string of text I just need the CLM*2022376004 part extracted to a new file. The input has rows and rows of strings like this. I'm not sure if this can be done in a batch script, but hopefully someone can help me out. Thank you for reading.


See More: Batch Script to extract parts of a string

Report •

May 28, 2010 at 09:28:45

for /f "tokens=1-2 delims=~" %%b in ("yourfile.txt") do (
  echo %%b >> newfile.txt
  echo removed %%a)

%%a will be all characters before the "~" and %%b will be what is after.

Report •

May 28, 2010 at 09:52:00
Thanks for the help Ace, but I'am still having a problem I ran the code you gave me but the newfile that gets created just contains yourfile.txt in it, I did make sure to change the input file to the name yourfile.txt just to test it out. The data I need isn't getting copied it is just writing out yourfile.txt in the new file. I don't know programming in dos batches too well so i'm sure it something im doing wrong. Any further help would be great. thanks

Report •

May 28, 2010 at 10:15:57
might be a different version of an OS you are using so try using TYPE like...

for /f "tokens=1-2 delims=~" %%b in ("type yourfile.txt") do (
  echo %%b >> newfile.txt
  echo removed %%a)

P.S. this code was written off the top of my head just to give you an idea of how it is done. I did not test it. I will leave the debugging up to you. Here is a good site to vivist to learn Batch Scripting...

Report •

Related Solutions

May 28, 2010 at 10:21:34
Sorry I should have been more clear on my OS. I'am using Windows XP and due to size limits on the limit my strings are actually written out like this:


and I just want to copy every instance of CLM*2010603054 to a new file. the numbers after CLM* do tend to change.

Report •

May 28, 2010 at 10:24:28
Thanks for the website Ace and for the help. I will take a look and hopefully get a better idea on what I should be doing.

Report •

May 28, 2010 at 19:59:02
Ace, i think used wrong quotes. needed this to make his version work:
for /f "tokens=1-2 delims=~" %%b in ('type yourfile.txt') do (

either that, or alternatively remove the TYPE and quotes around the filename:
for /f "tokens=1-2 delims=~" %%b in (yourfile.txt) do (
but i would maybe make suggestion:
@echo off & setlocal
for /f "tokens=2-3 delims=~*" %%a in (yourfile.txt) do >> newfile echo %%a*%%b
:: move /y newfile yourfile.txt

Report •

June 1, 2010 at 10:17:30
Oops sorry. That's what happens when you don't test.

Report •

June 1, 2010 at 21:22:58
Lol!! been there done that and still doing! :-)

Report •

Ask Question