The batch file command lines below can be used if the file output.txt
in directory of the batch file contains the lines:
"name" : "Bob",
"PhoneNumber" : "123-555"
"name" : "Mike",
"PhoneNumber" : "234-555"
"name" : "Amber",
"PhoneNumber" : "456-555"
The batch file is:
@echo off
setlocal EnableExtensions DisableDelayedExpansion
if not exist "%~dp0output.txt" echo File "%~dp0output.txt" not found.& exit /B 1
set "Name="
( echo name,PhoneNumber
for /F usebackq^ tokens^=1^,3^ delims^=^" %%I in ("%~dp0output.txt") do (
if "%%I" == "name" (set "Name=%%J") else if "%%I" == "PhoneNumber" (
set "PhoneNumber=%%J"
setlocal EnableDelayedExpansion
if "!Name:,=!" == "!Name!" (
echo !Name!,!PhoneNumber:,=!
) else (
echo "!Name!",!PhoneNumber:,=!
)
endlocal
)
)
)>"%~dp0Data.csv"
endlocal
This batch file creates in the batch file directory the CSV file Data.csv
with the lines:
name,PhoneNumber
Bob,123-555
Mike,234-555
Amber,456-555
If a name
contains a comma, the name is enclosed in "
in the CSV file Data.csv
. The code makes sure that a phone number does not contain a comma before writing it into the CSV file.
To understand the commands used and how they work, open a command prompt window, execute there the following commands, and read the displayed help pages for each command, entirely and carefully.
call /?
... explains %~dp0
... drive and path of argument 0 which is the batch file path always ending with a backslash.
echo /?
endlocal /?
exit /?
for /?
goto /?
if /?
set /?
setlocal /?
See also: