Replace specific text in csv via commandline

。_饼干妹妹 提交于 2019-12-01 13:20:28
@echo off
    setlocal enableextensions enabledelayedexpansion

    (for /f "tokens=*" %%f in (a.csv) do if not "%%f"=="" (
            set "line=%%f"
            set "line=!line:NULL=-1!"
            set "line=!line:N.A.=-2!"
            echo(!line!
    )) > b.csv

    endlocal

This will work if, as stated by OP, the file is in the format indicated, containing only integers, NULL and N.A., or at least it does not include special characters.

This uses a helper batch file called repl.bat from - https://www.dropbox.com/s/qidqwztmetbvklt/repl.bat

Place repl.bat in the same folder as the batch file or in a folder that is on the path.

It should be more robust and faster.

type file.csv |repl "NULL" "-1" |repl "N\.A\." "-2" >newfile.csv

Try this out:

@echo off
setLocal enableDelayedExpansion

set filename=input.txt
set originalText1=NULL
set "replacedText1=-1"
set "originalText2=N.A."
set "replacedText2=-2"

for /f "tokens=*" %%a in ('type %filename%') do (
    set "line=%%a"
    if defined line (
        call set "line=%%line:%originalText1%=%replacedText1%%%"
        call set "line=%%line:%originalText2%=%replacedText2%%%"
        echo !line!>> output.txt
    ) else (
        echo.
    )
)

This code will help you to replace all the instance of NULL to -1 and N.A. to -2. The result will then be stored in output.txt. Hope it helps.

P.S. Note that call set is needed as it will expand the variable that is passed on the same line.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!