簡體   English   中英

替換CSV字符串中的第n個元素

[英]Replace n-th element in CSV string

我嘗試替換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"
)

沒用 難道我做錯了什么 ?

@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是第二個令牌, %%b
您要編寫token1;token2;token3,"replacement string for the fourth token(%%d)";"rest of the line" (fifth token)

假設*字符沒有真正出現在您的數據中,並且也不包含任何? 標記,您可以使用以下代碼段:

@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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM