Reputation: 1407
In one text file I have this lines:
2014-10-09 00:00:00.000;1663;2014-10-09 12:38:46.000;A;"
";0;0;E/272
2014-10-09 00:00:00.000;1663;2014-10-09 12:38:46.000;A;"
";0;0;D/275
I need using a DOS batch file this new output:
2014-10-09 00:00:00.000;1663;2014-10-09 12:38:46.000;A;"";0;0;E/272
2014-10-09 00:00:00.000;1663;2014-10-09 12:38:46.000;A;"";0;0;D/275
And I have tried this solution:
for /f "delims=" %%a in (oldfile.txt) do (
echo/|set /p ="%%a%"
)>>newfile.txt
But the output is wrong, I don't have two lines in txt newfile but only one line:
2014-10-09 00:00:00.000;1663;2014-10-09 12:38:46.000;A;"";0;0;E/2722014-10-09 00:00:00.000;1663;2014-10-09 12:38:46.000;A;"";0;0;D/275
What am I missing?
What's wrong with this code?
Thank you in advance.
Upvotes: 2
Views: 6631
Reputation: 1
Empty lines may get ignored, but can be re appended by using echo.
for /f "usebackq delims=" %%A in ("%INTEXTFILE%") do (
set "Line=%%A"
if not "!FirstLine!"=="" (
if "!Line:~0,22!"=="!BeginSecondLine!" (
set "FirstLine=!FirstLine!!Line:~20!"
echo !FirstLine!>>"%OUTTEXTFILE%"
echo. >>"%OUTTEXTFILE%"
set "Line="
) else (
echo !FirstLine!>>"%OUTTEXTFILE%"
echo. >>"%OUTTEXTFILE%"
set "FirstLine="
)
)
if no t "!Line!"=="" (
if "!Line:~-1!"=="!EndFirstLine!" (
set "FirstLine=!Line!"
) else (
echo !Line!>>"%OUTTEXTFILE%"
echo. >>"%OUTTEXTFILE%"
)
)
)
Upvotes: 0
Reputation: 49186
New lines in double quoted values are absolutely valid in CSV files.
Why not using a text editor which supports Perl regular expression replaces?
For example running a Perl regular expression replace using as search string (?<=")\s+(?=";)
and an empty string as replace string would do the job.
There are console applications written for replacing strings in files. See
How can you find and replace text in a file using the Windows command-line environment?
But if you want to do this with a batch file for some unknown reason, take a look on batch code below working for your example.
@echo on
setlocal EnableDelayedExpansion
set "INTEXTFILE=oldfile.txt"
if not exist "%INTEXTFILE%" goto EndBatch
set "OUTTEXTFILE=newfile.txt"
if exist "%OUTTEXTFILE%" del "%OUTTEXTFILE%"
set "FirstLine="
set "EndFirstLine=""
set "BeginSecondLine= ";"
for /f "usebackq delims=" %%A in ("%INTEXTFILE%") do (
set "Line=%%A"
if not "!FirstLine!"=="" (
if "!Line:~0,22!"=="!BeginSecondLine!" (
set "FirstLine=!FirstLine!!Line:~20!"
echo !FirstLine!>>"%OUTTEXTFILE%"
set "Line="
) else (
echo !FirstLine!>>"%OUTTEXTFILE%"
)
set "FirstLine="
)
if not "!Line!"=="" (
if "!Line:~-1!"=="!EndFirstLine!" (
set "FirstLine=!Line!"
) else (
echo !Line!>>"%OUTTEXTFILE%"
)
)
)
:EndBatch
endlocal
Empty lines are removed by this batch file, too. This cannot be avoided as command for
ignores empty lines on parsing the file.
Upvotes: 1