Question

I have a problem with parsing a string, which consists only of directory path. For ex.,

My input string is Abc\Program Files\sample\

My output should be Abc//Program Files//sample

The script should work for input path of any length i.e., it can contain any no. of subdirectories. (For ex., abc\temp\sample\folder\joe)

I have looked for help in many links but to no avail. Looks like FOR command extracts only one whole line or a string (when we use ‘token’ keyword in FOR syntax) but my problem is that I am not aware of the input path length and hence, the no. of tokens.

My idea was to use \ as a delimiter and then extract each word before and after it (), and put the words to an output file along with // till we reach the end of the string.

I tried implementing the following but it did not work:

@echo off

FOR /F "delims=\" %%x in (orig.txt) do (
    IF NOT %%x == "" echo.%%x//>output.txt    
)

The file orig.txt contains only one line i.e, Abc\Program Files\sample\

The output that I get contains only: Abc//

The above output contains blank spaces as well after ‘Abc//’

My desired output should be: Abc//program Files//sample//

Can anyone please help me with this?

Regards,
Technext

Was it helpful?

Solution 4

Thanks for your input Kyra! I know it's easy in Shell or Perl but anyways, i have now got the solution.

Here it is:


type nul>output.txt

FOR /F "usebackq tokens=*" %%x in ("orig.txt") do (
    set LINE=%%x
    call set LINE=%%LINE:\=//%%
    call echo:%%LINE%%
) >>output.txt

Thanks hoang. I was about to post when I saw your reply.

OTHER TIPS

Have you tried pattern matching? I know in perl and Java you can do a simple replace that finds all of the "\" and replaces them with "//"

Example in perl:

my $var = "Abc\Program Files\sample\"
$var  =~ tr/\\/\/\//; 

Just look up pattern matching or regex

You could use simple string substition:

C:\>set myvariable=Abc\Program Files\sample\    

C:\>echo %myvariable%
Abc\Program Files\sample\

C:\>set myvariable=%myvariable:\=//%

C:\>echo %myvariable%    
Abc//Program Files//sample//

Using a loop and a temporary file, the following works for your scenario :

@echo off > output.txt
FOR /F "tokens=1,* delims=\" %%x in (orig.txt) do ( 
IF NOT %%y=="" echo %%x//%%y>>output.txt
)
:loop
@echo off > temp.txt
set /a stop=1
FOR /F "tokens=1,* delims=\" %%x in (output.txt) do (
IF NOT "%%y"=="" (
echo %%x//%%y>>temp.txt
set /a stop=0
) ELSE (echo %%x>>temp.txt)
)
IF NOT %stop%==1 (
move /Y temp.txt output.txt
) ELSE (goto end)
goto loop
:end
move /Y temp.txt output.txt

Given this input

Abc\Program Files\sample\
Another\Example\\\

you'll get the following output :

Abc//Program Files//sample
Another//Example

Pretty ugly isn't it ? ^^

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top