Windows shell 中的bat 脚本,如果行中存在另一个字符串,则替换某些字符串

问题描述 投票:0回答:1

我是 Windows 中批量编辑的新手,我对无法在 bat 文件中使用 powershell 命令感到非常困惑。

长话短说,我有这个输入文件:

The quick brown fox jumped over the lazy white dog
The quick red fox jumped over the lazy dog
The quick green wolf jumped over the lazy brown dog
The quick brown fox jumped over the lazy dog
The quick red lion jumped over the lazy dog
The quick green pig jumped over the lazy brown dog
The quick brown fox jumped over the lazy dog

如果句子包含术语“狐狸”,我想用白色替换棕色。 作为额外要求,只有第一次出现时我才想更换棕色。

我尝试使用 .contains 和 find,但当我尝试使用 if 条件的结果时,一切仍然变得混乱。

我能做到的最好的就是这个:

@echo on &setlocal
set "search=brown"
set "replace=white"
set "textfile=C:\JavaLogs\ReplaceDemo.txt"
set "newfile=C:\JavaLogs\Output.txt"
set lines=0
(
for /f "delims=" %%i in (%textfile%) do (
    set lines=echo %%i | findstr /C:"fox" |  measure -w -c -l
    echo %lines%
    if "%lines%">"0" echo "There is a fox"
    if "%lines%"=="0" echo "There is no fox"
    set %%i=%%i:%search%=%replace% echo(%%i>%newfile%)  

    else echo(!%%i!)>"%newfile%"
    ) 
)

但它仍然是垃圾。

最终结果将是这样的输出文件:

The quick white fox jumped over the lazy white dog
The quick red fox jumped over the lazy dog
The quick green wolf jumped over the lazy brown dog
The quick white fox jumped over the lazy dog
The quick red lion jumped over the lazy dog
The quick green pig jumped over the lazy brown dog
The quick white fox jumped over the lazy dog
string powershell batch-file batch-processing
1个回答
0
投票

我建议使用 PowerShell,特别是如果您是新手并且在 Windows 下学习脚本编写。

您想要在 PowerShell 下执行的操作示例是创建一个包含以下内容的 MyReplace.ps1 文件:

param (
    [Parameter(Mandatory=$true, ValueFromPipeline=$true, Position=1)]
    [string]$Text
)
if ($text -match 'fox') {
    $text -replace '(?=brown)brown(.*)', 'white$1'
}
else { 
    $text
}

然后您可以从 PowerShell 控制台窗口运行:

Get-Content C:\JavaLogs\ReplaceDemo.txt | % { .\MyReplace.ps1 $_ } 

这将运行您想要的逻辑并输出您的文本。

最后,如果您想将输出发送到另一个文件,您可以将上面的内容更改为:

Get-Content C:\JavaLogs\ReplaceDemo.txt | % { .\MyReplace.ps1 $_ } |  Set-Content C:\JavaLogs\Output.txt
© www.soinside.com 2019 - 2024. All rights reserved.