Remove backslashes from string so as to use that string in a FOR loop (for batch doc conversion)

StackOverflow https://stackoverflow.com/questions/23506153

  •  16-07-2023
  •  | 
  •  

Question

I'm trying to batch convert old word docs to docx using LibreOffice (the only program I can find that will still display the files with correct formatting) using the Windows 7 command line (via a batch file). I need to mirror the old folder/directory structure for all those files in creating the new ones. I have this almost working with the following:

for /R d:\docs %%I in (*) do (
soffice --headless --convert-to docx:"MS Word 2007 XML" --outdir "d:\docsfinal%%~pI" "%%I"
)

Here's the problem:

LibreOffice --outdir (output directory) will not accept a path that includes a trailing backslash. And that's exactly what %%~pI spits out-- the path of that variable with a trailing backslash. So I need to get rid of that backslash before inserting it in --outdir.

So after much googling and searching of stack exchange, I came up with this franken-code (I'm not a programmer, truthfully):

for /R d:\docs %%I in (*) do (
SETLOCAL enableextensions enabledelayedexpansion
set J=%%~pI
set K=%J:~0,-1%
soffice --headless --convert-to docx:"MS Word 2007 XML" --outdir "d:\docsfinal%K%" "%%I"
ENDLOCAL
)

But, when I run this the J variable does not get reset to the new value (from the new path that should be supplied through %%~pI) each time the loop loops. So all my files end up in one directory. It's like it sets J once and then always uses that value, no matter what it's set to each time through.

I'd be grateful for any pointers on what I'm doing wrong (other than being a non-programmer yet dabbling with the command prompt :)

Was it helpful?

Solution

You need to use delayed expansion if you are going to define and expand a variable within a FOR loop. You properly enabled delayed expansion, but you need to use set K=!J:~0,-1! instead of set K=%J:~0,-1%. Also use "d:\docsfinal!K!".

But there is a better (simpler) way that avoids delayed expansion :-)

for /R d:\docs %%I in (*) do for /f "eol=: delims=" %%J in ("%%I\..") do (
  soffice --headless --convert-to docx:"MS Word 2007 XML" --outdir "d:\docsfinal%%~pnxJ" "%%I"
)

Or even better yet, I think the following will work (simply append a dot to the path). But I haven't tested this.

for /R d:\docs %%I in (*) do (
  soffice --headless --convert-to docx:"MS Word 2007 XML" --outdir "d:\docsfinal%%~pI." "%%I"
)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top