Raghu Cheedalla
Raghu Cheedalla

Reputation: 27

Delete trailing spaces in a file for comparison using batch script

I created a batch file that runs some SQL and writes the output to a file.

Now I'm trying to compare this result data to move some files but the SQL output file seems to have trailing spaces resulting in wrong comparison.

How can I remove these trailing spaces?

FOR /F "delims=" %%R IN (C:\Test01.txt) DO IF Ready == %%R COPY /y C:\Test01.txt "

Test01 looks like

Returncode
-----------
No
Yes
Complete
Incomplete
Ready              

I am seeing trailing spaces and comparing it to Ready always results in a No

Upvotes: 2

Views: 1204

Answers (2)

dbenham
dbenham

Reputation: 130819

FOR variable expansion has modifiers that treat the value as a file specification and break it down into components

  • %%~dR = drive:
  • %%~pR = \path\
  • %%~nR = baseName
  • %%~xR = .extension

These modifiers also normalize the value into a canonical (standard) form.

Windows does not allow a file or folder name to end with space or dot, so the modifiers will trim trailing dots and spaces from the value. You can use this fact to trim the trailing spaces!

FOR /F "delims=" %%R IN (C:\Test01.txt) DO IF Ready == %%~nxR COPY /y C:\Test01.txt

This will only work properly if the value does not contain : \ or /. Also remember that it will also trim trailing dots. So a string like c:\my path\Ready. would also become Ready if you use %%~nxR.

There is an even simpler and more reliable solution that may work in your case. All of your lines consist of a single word (plus trailing spaces). If you can rely on that fact, then you can simply remove your DELIMS option and let FOR trim the spaces for you (the default DELIMS is space and tab).

FOR /F %%R in (C:\Test01.txt) DO IF Ready == %%R COPY /y C:\Test01.txt

If you are worried that some word could follow READY, in which case you don't want to COPY, then you could use

FOR /F %%R* in (C:\Test01.txt) DO IF Ready == %%R IF "%%S" == "" COPY /y C:\Test01.txt

Upvotes: 3

Tomalak
Tomalak

Reputation: 338208

You can use batch string processing to cut the first five letters (i.e., the length of the string "Ready") from the line.

This requires enabledelayedexpansion (see docs) and it works like this:

setlocal enabledelayedexpansion

for /f "delims=" %%R IN (Test01.txt) do (
  set str=%%R
  if "!str:~0,5!" == "Ready" copy /y Test01.txt "somewhere"
)

See more string manipulation tips - including a way to trim whitespace - here: http://www.dostips.com/DtTipsStringManipulation.php

Upvotes: 1

Related Questions