1

Being new to DOS, I am trying to write a batch file that replaces all the "|" by "," in files called test1.txt, test2.txt and output to files called test1.csv, test2.csv. It works fine for the first file but the second .csv file keeps the "|".

Here is my code:

@echo off
setlocal enabledelayedexpansion

for %%a in (test*.txt) do (
set line=%%a
type "!line:|=","!" > %%~na.csv
)

I read a thread mentioning that the "line" variable may be changed after parsing the block once, but I don't see how to fix the problem (I tried several modifications like "call" before "type" but still the same).

Any help would be great. Thanks !

lqdo2000
  • 351
  • 2
  • 5
  • 16

1 Answers1

1

Edited: These work here.

@echo off
setlocal enabledelayedexpansion
for %%a in (test*.txt) do (
  for /f "delims=" %%b in ('type "%%a" ') do (
   set "line=%%b"
   set "line=!line:|=,!"
   >> "%%~na.csv" echo !line!
  )
)

Using a helper batch file called repl.bat from - http://www.dostips.com/forum/viewtopic.php?f=3&t=3855 this will preserve blank lines and be more reliable.

@echo off
for %%a in (test*.txt) do type "%%a" | repl "\|" "," m > "%%~na.csv"
foxidrive
  • 40,353
  • 10
  • 53
  • 68
  • Only process the first line of test1.txt and put the second line of test1.txt in the second output file. Names of the 2 .csv files are also messed up with the first and second line of test1.txt respectively – lqdo2000 Aug 18 '13 at 06:34
  • Also, with your second code, only test1.csv is produced but it is empty – lqdo2000 Aug 18 '13 at 06:38
  • The second one works fine - it requires the helper batch file. I fixed the first code as I had reused %%a. Thanks. – foxidrive Aug 18 '13 at 06:46
  • I tried with other character to replace, and I noticed it doesn't work with tabs "\t". Do you known why? – lqdo2000 Aug 18 '13 at 08:05
  • because `/t` is not translated to , as you seem to expect. Just hit the key instead. Of course, you need an editor, that will NOT translate the TAB with some spaces. (Notepad.exe will work fine) – Stephan Aug 18 '13 at 08:21
  • So what do I have to replace `|` with? I tried `` but doesn't work. Same with the TAB key. I use Notepad++ – lqdo2000 Aug 18 '13 at 08:27
  • You are right! [link](http://stackoverflow.com/questions/455037/notepad-tabs-to-spaces) – lqdo2000 Aug 18 '13 at 08:36