查找并替换CSV中的文本,使用部分和通配符直到第一个分隔符



我有一个从SQL输出生成的csv,我正试图用通用字符串替换csv的部分字符串。我尝试过art、(总是让我笑)、FINDSTR和POWERSHELL,但我认为我的技能还不够,而且由于我规定的警告,谷歌搜索相当困难。

文本文件是这样的(示例数据)。

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-GCE替换2122-*的所有第一次迭代。

那么最终输出将是:

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将是好的。

希望这是有意义的?

(编辑/)

抱歉,错过了我的代码尝试。

Myfindstrattempt:

findstr /V /i /R '2122-.*' '2122-GCE' "E:path to filefile1.csv" > "E:path to fileoutput3.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

正如你在上面看到的,它被加了前缀,没有被替换。

MyFARTattempt:

E:path tofart "E:path to filefile1.csv" 2122-N* 2122-GCE
E:path tofart "E:path to fileoutput3.csv" 2122-D? 2122-GCE

我的PS1尝试在ISE中,我没有保存就关闭了。

编辑,我有一个ps窗口仍然打开:

((Get-Content -path E:path to filefile1.csv -Raw) -replace '2122-*','2122-GCE') | Set-Content -Path E:path to filefile2.csv

替换命令的一些迭代:-replace '[^2122]*'

type file1.csv | ForEach-Object { $_ -replace "2122-*", "2122-GCE" } | Set-Content file2.csv

看起来第一个数据值总是以非空值存在,不以;开始,必须始终用相同的值替换,第二个数据列包含所有数据行总是一个值,因此,在数据行中第一个数据值之后永远不会有,,

在这些条件下可以使用以下注释批处理文件:

@echo off
setlocal EnableExtensions DisableDelayedExpansion
set "SourceFile=E:path to filefile1.csv"
set "OutputFile=E:path to filefile2.csv"
if not exist "%SourceFile%" exit /B
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 /?
  • exit /?
  • for /?
  • goto /?
  • if /?
  • rem /?
  • set /?
  • setlocal /?

最新更新