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.