Convert .tsv file to .csv file with tab_delims using batch file

Viewed 44

i have some trouble about convert file tsv to file csv with .bat. Problem is i can't convert when i change data with tab and spaces

My current source

setlocal disableDelayedExpansion

set OUT_DIR1=%1
set input=%OUT_DIR1%\%2
set output=%OUT_DIR1%\%3
set IN_DIR=%4

type %IN_DIR%\*.tsv > %OUT_DIR1%\result.tsv

>%output% (         
    for /F "tokens=* delims=" %%a in (%input%) do (
    set "line="
    setlocal enableDelayedExpansion
    for %%b in (%%a) do set "line=!line!,%%b"
    echo !line:~1!
    endlocal
    )
)

My input file

0001    abc de mo1  abc
0001    a bc    de mo2  abc
0001    abc de mo3  a bc
0001    a bc    de mo4  a bc

My output i want

0001,abc,demo1,abc
0001,abc,demo2,abc
0001,abc,demo3,abc
0001,abc,demo4,abc

Please help me!!!!!!!!!!!!!!!!!!!

1 Answers
@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
rem The following settings for the source directory, destination directory,
rem filename, output filename are names
rem that I use for testing and deliberately include names which include spaces to make sure
rem that the process works using such names. These will need to be changed to suit your situation.

SET "sourcedir=u:\your files"
SET "destdir=u:\your results"
SET "filename1=%sourcedir%\q72797128.txt"
SET "outfile=%destdir%\outfile.txt"

:: variables that contain the obvious single characters

SET "space= "
SET "tab=   "

(
FOR /f "usebackqdelims=" %%b IN ("%filename1%") DO (
 SET "line=%%b"
 SET "line=!line:%space%=!"
 ECHO !line:%tab%=,!
)
)>"%outfile%"

TYPE "%outfile%"

GOTO :EOF

I can see no reason for the type line. It appears irrelevant.

Similarly, there appears to be no reason to disable delayedexansion, then re-enable it within the loop.

Your sample data contains no tabs, only spaces. I changed it so that tabs appeared after 0001, abc and before the last abc. It appears that you want to eliminate the spaces in demo.

So - assign the line to an ordinary variable, then use string-replace to delete the spaces and alter the tabs to commas.

Please note in "tokens=* delims=" , "tokens=*" is redundant.

Use set "var1=value" for setting STRING values - this avoids problems caused by trailing spaces.

Related