繁体   English   中英

Powershell替换添加空行

[英]Powershell replace adding an empty line

我有这个powershell代码,应该用新的字符串替换目录中每个文件中每个字符串的出现。 这可行,但是最后添加一个空行。 是什么原因导致的,如何才能避免这种情况?

$files = Get-ChildItem $currentDir *.* -recurse
foreach ($file in $files)
    {
    $find = "placeholder"
    $replace = "newvalue"
    $content = Get-Content $($file.FullName) -Raw
    $content -replace $find,$replace | Out-File $($file.FullName) 
    }

仅仅删除最后一行并不是一个好的解决方案,因为有时我的文件将包含一个我想保留的空行。

您可以使用-NoNewline参数来防止Out-File在文件末尾附加多余的行。

$content -replace $find,$replace | Out-File $($file.FullName) -NoNewline

注意:这是在PowerShell 5.0中添加的

我仅限于PS版本4,这就是我使用的

$ files = Get-ChildItem $ currentDir -递归

$find = "placeholder"
$replace = ""newvalue"    

foreach ($file in $files)
    {
    $content = Get-Content $($file.FullName) -Raw | ForEach-Object { $_ -replace $find,$replace}
    $content = $content -join "`r`n"

    $content | Set-Content  $($file.FullName)      
    }

请注意,这仅在可以将完整文件存储在内存中的情况下才有效。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM