替换CSV字符串中的第n个元素

时间:2016-08-22 12:57:33

标签: windows csv batch-file cmd

我尝试替换CSV字符串的第n个元素,而不知道他的值。例如,这是我的字符串:

*;*;*;element_to_replace;*;*

使用*未定义的字符串,它可以是任何内容。

所以我尝试使用:

for /F "delims=" %%w in (file\workstation) do (
    set line=%%w
    if !compt! NEQ 0 (
        set new_line=!line:*;*;*;*=*;*;*;new_value!
        @echo !new_line! >> file\tmp_workstation
    ) else (
        @echo !header_workstation! >> file\tmp_workstation
    )
    set /A "compt+=1"
)

它不起作用。我做错了吗?

2 个答案:

答案 0 :(得分:2)

@echo off 
setlocal enabledelayedexpansion
REM you want to replace token 4:
for /f "tokens=1-4,* delims=;" %%a in (t.csv) do (
   echo %%a;%%b;%%c;replaced;%%e
)

tokens=1-4,*表示:取前四个令牌,第五个令牌是"其余部分"。 %%a是第一个标记,%%b是第二个标记等。
你想写token1;token2;token3,"replacement string for the fourth token(%%d)";"rest of the line" (fifth token)

答案 1 :(得分:1)

假设*个字符不会出现在您的数据中,并且它也不包含任何?个标记,您可以使用以下代码段:

@echo off
setlocal EnableExtensions DisableDelayedExpansion

rem // Define constants here:
set "INFILE=file\workstation"
set "OUTFILE=file\tmp_workstation"
set "SEPARATOR=;"
set /A "COL_NUM=4"
set "COL_NEWVAL=new_value"

rem // A single redirection:
> "%OUTFILE%" (
    set "HEADER=#"
    rem // Read CSV file line by line:
    for /F usebackq^ delims^=^ eol^= %%L in ("%INFILE%") do (
        set "LINE=%%L"
        if defined HEADER (
            rem // Skip header from replacement:
            set "NEW_LINE=%%L"
            set "HEADER="
        ) else (
            set "NEW_LINE=" & set "SEP=" & set /A "IDX=0"
            rem // Toggle delayed expansion to not lose any `!`:
            setlocal EnableDelayedExpansion
            set "LINE=!LINE:"=""!^"
            rem // Use standard `for` loop to enumerate column values:
            for %%I in ("!LINE:%SEPARATOR%=","!") do (
                endlocal
                set /A "IDX+=1"
                set "ITEM=%%~I"
                setlocal EnableDelayedExpansion
                rem // Replace column value if index matches:
                if !IDX! EQU %COL_NUM% (
                    endlocal
                    set "ITEM=%COL_NEWVAL%"
                    setlocal EnableDelayedExpansion
                ) else (
                    if defined ITEM set "ITEM=!ITEM:""="!^"
                )
                rem /* Collect line string;
                rem    `for /F` loop to pass string beyond `endlocal` barrier: */
                for /F delims^=^ eol^= %%E in ("!NEW_LINE!!SEP!!ITEM!") do (
                    endlocal
                    set "NEW_LINE=%%E"
                    setlocal EnableDelayedExpansion
                )
                endlocal
                set "SEP=%SEPARATOR%"
                setlocal EnableDelayedExpansion
            )
            endlocal
        )
        rem // Output newly built line:
        setlocal EnableDelayedExpansion
        echo(!NEW_LINE!
        endlocal
    )
)

endlocal
exit /B