Replace a specific character in CSV

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
Mahlzeit20
Posts: 2
Joined: 19 Apr 2021 15:16

Replace a specific character in CSV

#1 Post by Mahlzeit20 » 19 Apr 2021 15:24

Hi together,

I really love this forum and hope I can find a solution.

I already tried to find something in the search, but I wasn't able to get a solution.

There is a .csv file with a changing order number like 68688-74747-473.
We need to replace the "-" into a "/" - but only in the column 1.

Other columns can also contain the character "-" (e.g. phone number or house number), they don't should be changed.

Maybe I'm too silly for that :oops: I hope someone can help me.

Regards
Thomas

aGerman
Expert
Posts: 4110
Joined: 22 Jan 2010 18:01
Location: Germany

Re: Replace a specific character in CSV

#2 Post by aGerman » 19 Apr 2021 16:19

Pretty similar: viewtopic.php?f=3&t=10035

Code: Select all

@if (0)==(0) echo off &setlocal
set "infile=test.csv"
set "outfile=out.csv"
set "separator=;"

cscript //nologo //e:jscript "%~fs0" "%infile%" "%outfile%" "%separator%"
goto :eof @end

var oFSO = new ActiveXObject('Scripting.FileSystemObject'),
    oInFile = oFSO.OpenTextFile(WScript.Arguments(0)),
    oOutFile = oFSO.OpenTextFile(WScript.Arguments(1), 2, true),
    delim = WScript.Arguments(2),
    line = '',
    arr = [],
    idx = 0;

while (!oInFile.AtEndOfStream) {
  line = oInFile.ReadLine();
  arr = line.split(delim);
  arr[0] = arr[0].replace(/-/g, "/");
  oOutFile.WriteLine(arr.join(delim));
}
oInFile.Close();
oOutFile.Close();
Steffen

Aacini
Expert
Posts: 1693
Joined: 06 Dec 2011 22:15
Location: México City, México

Re: Replace a specific character in CSV

#3 Post by Aacini » 19 Apr 2021 22:51

Code: Select all

@echo off
setlocal EnableDelayedExpansion

(for /F "tokens=1* delims=," %%a in (input.txt) do (
   set "col1=%%a"
   echo !col1:-=/!,%%b
)) > output.txt
input.txt

Code: Select all

68688-74747-473, Col-num-2, Col-num-3
88686-47474-374, Num-col-2, Num-col-3
output.txt

Code: Select all

68688/74747/473, Col-num-2, Col-num-3
88686/47474/374, Num-col-2, Num-col-3
Antonio

Mahlzeit20
Posts: 2
Joined: 19 Apr 2021 15:16

Re: Replace a specific character in CSV

#4 Post by Mahlzeit20 » 04 May 2021 07:07

Thank you Steffen and Antonio!!!!! You are the best!

Post Reply