Page 1 of 1

processing string from file

Posted: 28 Feb 2012 22:11
by Captcha142
I have been working (per request of a challenge) on a batch script to process a text file opened with it, and eventually want to renotate the .txt into batch

However, simply prep-ing the file for processing is throwing problems

I have two files comp.bat and text.txt

code.bat

Code: Select all

@echo off
set /p inputFile=<%1
echo %inputFile%
for /f "tokens=1 delims=;" %%a in ("%inputFile%") do set a=%%a;&set inputFile=%inputFile:%%a%%="%
echo %inputFile%
echo %a%
pause


text.txt

Code: Select all

print ("Hello World!");this is pointless code;


The current %'s has gotten the closest to what I want (to break the string into two, putting part 1 into variable a, and leaving the rest in inputFile for later processing), but instead, inputFile becomes %a%, when I want to remove that from the string, not make it equal it

Re: processing string from file

Posted: 28 Feb 2012 22:32
by foxidrive
Does this do what you want?

Code: Select all

@echo off
set /p inputFile=<%1
echo %inputFile%
for /f "tokens=1,* delims=;" %%a in ("%inputFile%") do (
set "a=%%a;"
set "b=%%b"
)
echo %b%
echo %a%
pause

Re: processing string from file

Posted: 28 Feb 2012 22:39
by Captcha142
Yes! Thank you!

However, why did you put a=%%a; in quotes?
Is there reason for this syntax?
(for is the my least understood of cmd commands, so link to reference isn't discouraged . . .)

Re: processing string from file

Posted: 28 Feb 2012 22:44
by foxidrive
The outside quotes allow you to include poison characters in a variable, and I do it by habit now as it doesn't include the quotes in the variable itself.

In your case they aren't strictly necessary.

Re: processing string from file

Posted: 28 Feb 2012 23:17
by Captcha142
One last tangential question:
How do you make "for" repeat until there are no more delimiters, ie.

Code: Select all

for /f "tokens=1, *. delims=;" %%a in ("%inputFile%") do (
...
)


when *. is the repeating anychar (to cycle until no delimiters left)

Re: processing string from file

Posted: 29 Feb 2012 02:41
by foxidrive
Captcha142 wrote: How do you make "for" repeat until there are no more delimiters,



It depends. If the number of tokens is known then you would use something like one of these.

"tokens=1-10 delims=;"
"tokens=1,2,3,4,5,6,7,8,9,10 delims=;"
"tokens=1,5,7 delims=;"

Another way is to parse the entire line character by character.

The exact makeup of the text can help to decide which is the easiest method.