Tama Aka
Tama Aka

Reputation: 13

replace unneeded spaces with commas in txt using batch

I have a text file that contains some information and looks like this:
7253 198760.294 533963.581
7373 198752.213 533954.046
739CT 198751.288 533952.902

In every line there are parameters that has spaces between them but the spaces (not tabs) are for ease or reading only.

I need it to look like this:
1550,168040.682,630305.751,
1575,168023.241,630287.837,
15964TS,168008.317,630272.508,

Here is my code:

@echo off
setlocal EnableDelayedExpansion
set LF=^


set "content="

for /f "delims=" %%x in (input.txt) do (
  set "content=!content!%%x!LF!"
)

:loop
if defined content (
  set "new=!content:  = !"
  if "!new!" neq "!content!" (
    set "content=!new!"
    goto :loop
  )
)
if defined content if "!str:~0,1!" equ " " set "content=!str:~1!"
if defined content if "!str:~-1!" equ " " set "content=!str:~0,-1!"

echo(!content!
set string=!content! & echo !string: =,! > output.txt
endlocal

pause > null

It turns everything in one line and connects between everything without spaces.

Upvotes: 1

Views: 34

Answers (1)

Stephan
Stephan

Reputation: 56180

Concatenation to a single string is dangerous, because of limited max string length. Better process each line on it's own:

(for /f "tokens=1-3" %%a in (infile.txt) do ( 
    echo %%a,%%b,%%c,
))>outfile.txt

note: empty lines will be ignored (will get lost)

Upvotes: 1

Related Questions