0

I was writing a windows batch script to convert pipe delimited file to comma delimited. When i run it for a single file it does the conversion but when I am running it for the files in a folder it does not.

I have the code written for single file but it does not loop thru the folder..


@echo off

set "INPUT=%C:\temp\source\*.csv"
set "OUTPUT=%C:\temp\dest\"

setlocal EnableExtensions DisableDelayedExpansion



> "%OUTPUT%" (
for %%F in (%*) do
(
    delims^=^ eol^= %%L in ("%INPUT%") do (
        set "LINE=%%L"
        setlocal EnableDelayedExpansion
        echo(!LINE:^|^=,!
        endlocal
    )
)
)
endlocal
exit /B

i want to run the script on all the files in the folder

Veejay
  • 3
  • 5
  • 1
    I would suggest that you fix the code so that it works for one file before extending it to work for multiple files. Also as the files you've got are `.csv`, I'd suggest you use [tag:powershell]'s `import-csv` and `export-csv` for this task instead: `Import-Csv -Path '' -Delimiter '|' | Export-Csv -Path '' -NoTypeInformation`. Even if your files are not true `.csv`'s, _(separated doublequoted strings)_, you could still consider using `powershell.exe`: `(Get-Content -Path '') -Replace '\|',',' | Set-Content -Path ''`. – Compo May 24 '19 at 12:13
  • let me try that – Veejay May 25 '19 at 05:40
  • forgot to mention.. it works for single file.. i want to it run thru the folder and do the same on all the file in the folder – Veejay May 25 '19 at 05:44
  • [possible duplicate](https://stackoverflow.com/questions/42288195/batch-script-quicker-echo-output-to-a-csv-file-in-a-for-loop) – Stephan May 25 '19 at 10:54

1 Answers1

1

Here are my two based comments, expanded for multiple files:

$folderPath = 'C:\temp\source\'
$folderPathDest = 'C:\temp\dest\'
Get-ChildItem $folderPath -Name -Filter *.csv |
ForEach-Object {
    $filePath = $folderPath + $_
    $filePathdest = $folderPathDest + $_
    Import-Csv -Path $filePath -Delimiter '|' |
    Export-Csv -Path $filePathDest –NoTypeInformation
}
$folderPath = 'C:\temp\source\'
$folderPathDest = 'C:\temp\dest\'
# As the pipe is a special character we need to escape it with a backslash
$stringToReplace = '\|'
$stringToAdd = ','
Get-ChildItem $folderPath -Name -Filter *.csv |
ForEach-Object {
    $filePath = $folderPath + $_
    $filePathdest = $folderPathDest + $_
    (Get-Content -Path $filePath) -Replace $stringToReplace,$stringToAdd |
    Set-Content -Path $filePathdest
}

In the latter, if using + you can also include the -Raw option to Get-Content, i.e. (Get-Content -Path $filePath -Raw)

Compo
  • 36,585
  • 5
  • 27
  • 39