我有一個從 SQL 輸出生成的 csv,我試圖用通用字串替換 csv 的部分字串。我嘗試過 FART,(總是讓我發笑)、FINDSTR 和 POWERSHELL,但我認為我的技能不夠,而且由于我規定的警告,Google 搜索非常困難。
txt檔案是這樣的(樣本資料)。
course_id,user_id,role,status
2122-DAC00002,123456,sometxt,active
2122-DAC00002,13456,sometxt,active
2122-DAC00010/1,987654,sometxt,active
2122-DAC00010,55669988,sometxt,active
2122-DAC00010/2,112233,sometxt,active
2122-DAC00010,852349,sometxt,active
標題可以忽略,第一部分是我需要整體更改的部分,因此搜索2122-*直到第一個,(2122-*可能略有不同的字符長度,但將始終停在,分隔符處,然后2122-*用2122-GCE.
所以最終輸出將是:
course_id,user_id,role,status
2122-GCE,123456,sometxt,active
2122-GCE,13456,sometxt,active
2122-GCE,987654,sometxt,active
2122-GCE,55669988,sometxt,active
2122-GCE,112233,sometxt,active
2122-GCE,852349,sometxt,active
我需要自動化這個,所以在一個.bat檔案中,或者一個.ps1會很好。
希望這是有道理的?
[編輯 /]
抱歉,錯過了我的代碼嘗試。
我的findstr嘗試:
findstr /V /i /R '2122-.*' '2122-GCE' "E:\path to file\file1.csv" > "E:\path to file\output3.csv"
findstr 輸出:
course_id,user_id,role,status
2122-GCENAC00025,123456,sometxt,active
2122-GCENAC00025,568974,sometxt,active
2122-GCENAC00025,223366,sometxt,active
2122-GCENAC00025,987654,sometxt,active
正如你在上面看到的,它的前綴而不是替換。
我的FART嘗試:
E:\path to\fart "E:\path to file\file1.csv" 2122-N* 2122-GCE
E:\path to\fart "E:\path to file\output3.csv" 2122-D? 2122-GCE
我的PS1嘗試是在 ISE 中,我沒有保存就關閉了。
編輯,我有一個 ps 視窗仍然打開:
((Get-Content -path E:\path to file\file1.csv -Raw) -replace '2122-*','2122-GCE') | Set-Content -Path E:\path to file\file2.csv
替換命令的一些迭代: -replace '[^2122]*'
type file1.csv | ForEach-Object { $_ -replace "2122-*", "2122-GCE" } | Set-Content file2.csv
uj5u.com熱心網友回復:
看起來第一個資料值總是與一個非空值一起存在,而不;是以相同的值開頭,并且必須始終替換為相同的值,并且第二個資料列在所有資料行上始終包含一個值,因此永遠不會,,在第一個之后資料行中的資料值。
在這些條件下可以使用以下帶注釋的批處理檔案:
@echo off
setlocal EnableExtensions DisableDelayedExpansion
set "SourceFile=E:\path to file\file1.csv"
set "OutputFile=E:\path to file\file2.csv"
if not exist "%SourceFile%" goto :EOF
rem Read just the header row from source CSV file and
rem create the output CSV file with just this line.
for /F "usebackq delims=" %%I in ("%SourceFile%") do (
>"%OutputFile%" echo(%%I
goto DataRows
)
rem Process just all data rows in source file by skipping the header row
rem with splitting each line into two substrings using the comma as string
rem delimiter with first substring assigned to loop variable I and not used
rem further and everything after first series of commas assigned to the
rem next but one loop variable J according to the ASCII table. The command
rem ECHO is used to output the first fixed data value and a comma and the
rem other data values of each data row. This output is appended to just
rem created output CSV file.
:DataRows
(for /F "usebackq skip=1 tokens=1* delims=," %%I in ("%SourceFile%") do echo 2122-GCE,%%J)>>"%OutputFile%"
endlocal
要了解使用的命令及其作業原理,請打開命令提示符視窗,在那里執行以下命令,并仔細閱讀為每個命令顯示的所有幫助頁面。
echo /?endlocal /?for /?goto /?if /?rem /?set /?setlocal /?
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/322043.html
