清理CSV文件

时间:2013-07-14 06:55:49

标签: batch-file

我使用.bat文件移动每天创建的CSV。我现在需要清理它:

  • 找到并将“ - ”替换为0
  • 找到并用0
  • 替换空单元格
  • 删除所有空格

CSV只有20行。

3 个答案:

答案 0 :(得分:2)

不知道,你需要什么。如果这对你不起作用,请解释一下:

for /f "delims=" %%a in (old.csv) do (
  set "line=%%a"
  setlocal enabledelayedexpansion
  set "line=!line: =!"
  set "line=!line:-=0!"
  >> new.csv echo(!line!
  endlocal
)

答案 1 :(得分:0)

批处理文件不是一个好的工具。使用PowerShell会好得多:

(Get-Content 'C:\path\to\in.csv') `
  -replace ' ', '' `
  -replace '-', '0' `
  -replace '^,', '0,' `
  -replace ',$', ',0' `
| % {
  while ($_ -match ',,') { $_ = $_ -replace ',,', ',0,' }
  $_
} | Out-File 'C:\path\to\out.csv'

甚至是VBScript:

Set fso = CreateObject("Scripting.FileSystemObject")

inFilename  = "C:\path\to\in.csv"
outFilename = "C:\path\to\out.csv"

Set inFile  = fso.OpenTextFile(inFilename)
Set outFile = fso.OpenTextFile(outFilename, 2, True)

outFile.WriteLine inFile.ReadLine  'write header
Do Until inFile.AtEndOfStream
  line = inFile.ReadLine

  line = Replace(line, " ", "")
  line = Replace(line, "-", "0")
  If Left(line, 1) = "," Then line = "0" & line
  If Right(line, 1) = "," Then line = line & "0"
  Do While InStr(line, ",,") > 0
    line = Replace(line, ",,", ",0,")
  Loop

  outFile.WriteLine line
Loop

inFile.Close
outFile.Close

答案 2 :(得分:0)

@ECHO OFF
SETLOCAL
(
FOR /f "delims=" %%i IN (yourfile.csv) DO (
 SET "line=%%i"&CALL :process
)
)>newcsv.csv
GOTO :EOF

:process
SET line=%line: =%
SET line=%line:-=0%
SET line2=%line%
SET line=%line:,,=,0,%
IF NOT "%line%"=="%line2%" GOTO process
IF "%line:~0,1%"=="," SET line=0%line%
ECHO %line%
GOTO :EOF

现在,interweb仙女终于重新登上了,这是我的版本......