Powershell Replace函数用于替换输出中的空行。请更正
我试图在文件中找到SyncIDE=0单词,然后在“=”后面的数字中添加前缀,如果文件包含SyncIDE=(anyinteger),则添加整数1作为前缀,SyncIDE=1(anyinteger)。ex SyncIDE=0,则应为SyncIDE=10 我相信代码在某种程度上是正确的,但替换函数不起作用,请帮助 输入文件 AppRemote=\app\u服务器的路径\u\VG\Login\VG.exe xxx kdfk 同步=1 djhdk SyncIDF=1 试验 输出文件 AppRemote=\app\u服务器的路径\u\VG\Login\VG.exe xxx kdfk djhdk SyncIDF=1 试验Powershell Replace函数用于替换输出中的空行。请更正,powershell,replace,Powershell,Replace,我试图在文件中找到SyncIDE=0单词,然后在“=”后面的数字中添加前缀,如果文件包含SyncIDE=(anyinteger),则添加整数1作为前缀,SyncIDE=1(anyinteger)。ex SyncIDE=0,则应为SyncIDE=10 我相信代码在某种程度上是正确的,但替换函数不起作用,请帮助 输入文件 AppRemote=\app\u服务器的路径\u\VG\Login\VG.exe xxx kdfk 同步=1 djhdk SyncIDF=1 试验 输出文件 AppRemote=\
它将替换空行,而不是SyncIDE=11,因此,在您的代码中,您试图实现的内容存在一些错误行为。 首先-在代码中,您试图查找
SyncIDE=1
(在问题中,您是说您正在查找SyncIDE=0
)
然后-您说要添加前缀,但在代码中添加了后缀($CharArray[1]+=1
)
Get Content
返回一个字符串数组,因此您必须在脚本中执行相应的操作,最好是对其进行迭代。另外-请记住-replace
使用正则表达式
我重构了您的代码,并提出了如下建议:
$SEL = Select-String -Path D:\PS\input.txt -Pattern "SyncIDE=1" | select-object -ExpandProperty Line
$file= 'D:\PS\input.txt'
$find= Select-String -Path D:\PS\input.txt -Pattern "SyncIDE=1" | select-object -ExpandProperty Line
if ($SEL -ne $null)
{
$CharArray =$SEL.Split("=")
$CharArray[1] += 1
$final= write-host "$($Chararray[0])=$($charArray[1])"
echo $final
ECHO $find
(Get-Content -path D:\PS\input.txt) -replace $find,'IDE=11' | Set-Content -Path D:\PS\output.txt
}
else
{
echo Not Contains String
}
输入:
$file= "C:\Temp\input.txt";
$outFile = 'C:\Temp\output.txt';
$pattern = "SyncIDE=1"
$find = Select-String -Path $file -Pattern $pattern | select-object -ExpandProperty Line;
$find = $find.Trim();
if ($null -ne $find)
{
$CharArray = $find.Split("=");
$final = "$($Chararray[0])=1$($charArray[1])";
Write-Output "FINAL is $final";
(Get-Content -path $file) | Foreach-Object {
#iterating through all lines in file and replacing the content
$_ -replace $find, $final;
} | Set-Content -Path $outFile;
}
else
{
Write-Output "Does not contain $pattern";
}
输出:
AppRemote=\path_of_app_server\VG\Login\vg.exe
xxx
kdfk
SyncIDE=1
djhdk
SyncIDF=1
Test
谢谢你@Grzegorz-Ochlik,成功了。谢谢你的更正。我会努力的。
AppRemote=\path_of_app_server\VG\Login\vg.exe
xxx
kdfk
SyncIDE=11
djhdk
SyncIDF=1
Test