The Windows command interpreter executing a batch file is designed for running commands and executables, but not for editing text or binary files. Therefore nearly all other scripting or programming languages are better for this CSV file editing task.
How can you find and replace text in a file using the Windows command-line environment? contains lots of solutions for searching and replacing strings in a file mainly using applications or other scripting languages.
One of the provided solutions is JREPL.BAT written by Dave Benham which is a batch file / JScript hybrid. Microsoft's JScript supports regular expression replaces. So whenever a simple regular expression search and replace in Perl like regex syntax can be performed on a text file with a text editor, it can be done usually also with jrepl.bat from within a batch file.
The batch code below expects jrepl.bat in same directory as the batch file containing the posted command lines. The file to modify is specified twice in this batch file with name DataFile.csv
.
@echo off
if not exist "DataFile.csv" goto :EOF
if not exist "%~dp0jrepl.bat" goto :EOF
call "%~dp0jrepl.bat" "(\|[01][0-9]/[0-3][0-9]/(?:19|20)[0-9][0-9]) (?=[0-9]:[0-5][0-9]\|)" "$1 0" /F "DataFile.csv" /O -
The search expression is written to find a date with time between two |
in format MM/DD/YYYY h:mm
and inserts 0
after the space character before single digit hour. Century of year must be 19
or 20
.
The search string finds the date/time in this format anywhere in line because I think this is better for the future in case of date/time string ever changes its field position in the line. It would be also possible to limit this search/replace to fourth |
delimited field value with the search string:
^((?:[^|]*\|){3}[01][0-9]/[0-3][0-9]/(?:19|20)[0-9][0-9]) (?=[0-9]:[0-5][0-9]\|)
DataFile.csv
is modified directly by this batch script. Replacing -
at end of jrepl.bat command line by a file name produces a new file being a copy of DataFile.csv
with all hour values converted to two digit values.