Redirecting Ouput Issue.

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
CodedZyntaX
Posts: 15
Joined: 07 Dec 2011 14:34

Redirecting Ouput Issue.

#1 Post by CodedZyntaX » 08 Dec 2011 00:27

Hi Guys,

I need help. I have a bat file (strlen.bat) that will calculate the length of a string.

Example usage 1:

strlen "Hello World"

Output:

11 (The quotes are removed)

strlen ""Hello World"

Output:

12

Now I want to transfer the output to variable I typed in this code in my "sample.bat":

strlen ""Hello World" > tmp

set /p len =< tmp

However instead of redirecting the output to tmp and from tmp to the variable %len% the output goes to the command line. It didn't work as expected because of the extra quote but what if I really want to include it how will I redirect it to a file?

Please me on this.

orange_batch
Expert
Posts: 442
Joined: 01 Aug 2010 17:13
Location: Canadian Pacific
Contact:

Re: Redirecting Ouput Issue.

#2 Post by orange_batch » 09 Dec 2011 04:54

You don't want to use a temp file. strlen should already set the length to a variable which you can use or transfer to another variable. If it doesn't, modify it.

For any command that outputs to the screen, you can catch that output and set it to a variable using:

Code: Select all

for /f "delims=" %%a in ('command goes here') do set "myvar=%%a"

dbenham
Expert
Posts: 2461
Joined: 12 Feb 2011 21:02
Location: United States (east coast)

Re: Redirecting Ouput Issue.

#3 Post by dbenham » 09 Dec 2011 11:12

orange_bat is correct in that the use of a temp file is probably not the best solution.

But it can be done by escaping the leading quote.

Code: Select all

strlen ^""Hello World" > tmp
set /p len =< tmp

However, I think you will be happier if you follow the advice of orange_batch.

I would take it one step farther - Your strlen batch file (or any function for that matter) will be more robust if it takes the name of a variable containing a string as an argument instead of a string literal. Passing string literals can be frighteningly complex. One year ago I naively started a utility batch script that was a callable library of functions. Many of my functions took string literal arguments. After months of work, I abandoned the project because it became much too complex.

Dave Benham


Dave Benham

CodedZyntaX
Posts: 15
Joined: 07 Dec 2011 14:34

Re: Redirecting Ouput Issue.

#4 Post by CodedZyntaX » 09 Dec 2011 21:45

I will surely follow these steps and apply it in my my new batch files.

I'm just an intermediate when it comes to batch programming however I'm really willing to stretch my boundaries.

Thank you dbenham and orange_batch for all these tips.

Post Reply