1

I have a file of the following format. Each line is a record of three values separated by |. I have written a batch script to validate whether each line has 3 records in it and report if there are any bad records(less or more than 3 values)

VALUE11|VALUE12|VALUE13|
VALUE21|VALUE22|VALUE23|
VALUE31|VALUE32|VALUE33|

PSUEDO CODE:

For each line in the file, DO
(1) Read line to a variable.
(2) Write to a temporary file and get file length.
(3) Remove | from the line.
(4) Write this modified line to temporary file and get file length.
(5) The difference between the two computed lengths gives the value count

Code:

@echo off
setlocal EnableDelayedExpansion
set /A column_count=3
set file_name=%1  

for /f "delims=" %%m in (!file_name!) do (
  set current_line=%%m
  echo.!current_line!>temp_file  

  :: Get length
  for %%s in (temp_file) do set /a curr_line_length=%%~zs  

  :: Remove |
  set "current_line_withoutpipes=!current_line:|=!"
  echo.!current_line_withoutpipes!>temp_file  

  :: Get new length
  for %%s in (temp_file) do set /a current_line_withoutpipes_length=%%~zs  

  :: Diff gives the pipe count 
  set /A line_column_count=!curr_line_length!-!current_line_withoutpipes_length!  

  if !column_count! EQU !line_column_count! (
            echo Good record
    ) else (
            echo bad record
    )   
  )
  endlocal

Problem: The problem comes when there are ! in the file and DelayedExpansion is set. The characters between two ! are getting truncated when they are set to a variable. In order to over come the problem, I put endlocal and then set DelayedExpansion again. With this change, the problem of ! is resolved but the variables defined before "endlocal" are no longer available after the "endlocal" statement.

Changed Code:

 .
 .
 for /f "delims=" %%m in (!file_name!) do (  
   endlocal & set current_line=%%m  
   setlocal EnableDelayedExpansion  
   echo.!current_line!>temp_file  
   .
   .

Appreciate if someone could help!! NOTE: The actual file contains hundreds of records.

user1270817
  • 31
  • 1
  • 3

1 Answers1

1

You could use a setlocal instead of an endlocal in the beginning.

for /f "delims=" %%m in (!file_name!) do (
  setlocal DisableDelayedExpansion
  set "current_line=%%m"
  setlocal EnableDelayedExpansion
  echo(!current_line!>temp_file  
  ...
  endlocal
  endlocal
)

But even this fails when a line begins with a ; and empty lines are dropped too.

For a complete solution you could read Batch files: How to read a file?

Community
  • 1
  • 1
jeb
  • 78,592
  • 17
  • 171
  • 225
  • Toggling of delayedexpansion only works for certain number of times with in a loop. Once the maximum count is reached, the toggling does not works. – user1270817 Nov 19 '15 at 15:32
  • Toggling works unlimited, but it's important that you add the same amount of `endlocal` – jeb Nov 19 '15 at 18:41