搜索字符串并替换文件中的整行

时间:2019-05-23 11:38:48

标签: powershell

我想在文件中搜索字符串,并用命令返回的值替换整行。但是由于某种原因,脚本不会更新文件中的值。

Ex:在文件中搜索$ FileName,并将该行替换为$ key变量中的值$ FileName = truncate_20190523.log,该变量的值源自$ NewFile变量。

$LogName = "Test.Log"

$FullPath = "\\etldev\logs"

$NewFile = Get-ChildItem -Path '\\etldev\logs\truncate_*' | Sort-Object LastWriteTime -Descending | Select-Object -First 1 | Select-Object -ExpandProperty Name

$Key = "`$FileName`=$NewFile"

$Line = Get-Content -Path $FullPath\$LogName | Select-String `$FileName` | Select-Object -ExpandProperty Line

(Get-Content -Path $FullPath\$LogName -Raw).Replace('$Line', $Key)| Set-Content -Path $FullPath\$LogName

1 个答案:

答案 0 :(得分:1)

看看您的$ Line变量。其中应该有整个日志文件。 像这样尝试:

perl -ne '/regex/ && $k++;$k!=0 && $k++ && $k=='"$lnb"'+2 && (print,$k=0)' my_file
相关问题