我需要在单个文件上执行多个查找和替换操作。设置如下:
文本数据-File.txt 替换数据-File2.txt
File2.txt的结构如下:
ABC,XYZ
MNB,OPI
GHI,TRY
第一列是我的原始名称(例如ABC),并替换为第二个名称(例如XYZ)。这必须在原始File.txt中完成
我可以编写代码来进行单个更改或将名称从ABC递增到ABC_Date,但是我对如何循环以及从名称读取和读取名称感到困惑。
感谢您的帮助。
我能够通过将以下答案汇总在一起来解决此问题: How can you find and replace text in a file using the Windows command-line environment?
How do you loop through each line in a text file using a windows batch file?
代码是:
for /F "tokens=1,2,3" %%i in (myfile.txt) do call :process %%i %%j %%k
goto thenextstep
:process
@echo %1
@echo %2
cscript replace.vbs "C:\newfile.txt" "%1" "%2"
goto :EOF
replace.vbs
Const ForReading = 1
Const ForWriting = 2
strFileName = Wscript.Arguments(0)
strOldText = Wscript.Arguments(1)
strNewText = Wscript.Arguments(2)
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(strFileName, ForReading)
strText = objFile.ReadAll
objFile.Close
strNewText = Replace(strText, strOldText, strNewText)
Set objFile = objFSO.OpenTextFile(strFileName, ForWriting)
objFile.Write strNewText 'WriteLine adds extra CR/LF
objFile.Close
答案 0 :(得分:0)
在这里,这是示例powershell代码,用于替换另一个文件中的多个单词。您必须更改$file1Text
值和$file2Text
值
$file1Text = "this is sample text. You have to get the text from file" ; # your file1 data
$file2Text = "this,here it","text,data","file,physical file" # your file2 lines
$finalText = $file1Text ; # Temp variable [ optional ] : you can use file1Text directly
foreach ($str in $file2Text)
{
$split = $str.Split(',')
$find = $split[0]
$replace = $split[1]
$finalText = $finalText.Replace($find,$replace)
}
cls
"Original Text : " + $file1Text
"Replaced Text : " + $finalText