【问题标题】:Prevent Powershell from adding new line at the end of file防止 Powershell 在文件末尾添加新行
【发布时间】:2023-03-18 21:21:01
【问题描述】:

我需要替换多个子文件夹中文件中的 HTML 实体,因此我使用了此处建议的 PowerShell 脚本:https://stackoverflow.com/a/2837891

但是,该脚本在文件末尾添加了一个额外的新行,我想避免这种情况。在该线程 (https://stackoverflow.com/a/2837887) 的下一条评论中列出了另一个脚本,它应该完全满足我的需要,但是当我尝试运行它时它不起作用。

这是我的脚本:

$configFiles = Get-ChildItem . *.xml -rec
foreach ($file in $configFiles)
{
    (Get-Content $file.PSPath) |
    Foreach-Object { $_ -replace '&# 8211;','–' } |
    Foreach-Object { $_ -replace '&# 160;',' ' } |
    Foreach-Object { $_ -replace '&# 8221;','”' } |
    Set-Content $file.PSPath
}

我需要做的就是不要在末尾添加新行。

提前谢谢你!

【问题讨论】:

    标签: powershell newline


    【解决方案1】:

    PowerShell v5+ 支持-NoNewline 开关和Set-Content cmdlet(以及Add-ContentOut-File)。

    如果您运行的是早期版本,则必须直接使用 .NET Framework,如 one of the answers you link to 中所示。

    警告-NoNewline 不仅仅意味着 尾随 换行符被省略,而是 所有 输入对象都是 直接连接,没有分隔符(并且没有添加尾随换行符)。
    如果您的输入是单个多行字符串,如下所示,-NoNewLine 将按预期工作,但如果您有一个 array 字符串,您只想用换行符编写 between em> 他们,而不是一个尾随,你必须做类似的事情:
    (('one', 'two', 'three') -join "`n") + "`n" | Set-Content -NoNewLine $filePath)。
    另请参阅:我的this answer


    顺便说一句:不需要多次ForEach-Object 调用 甚至是foreach 声明;您可以在一个管道中完成所有操作(PSv3+,由于 Get-Content -Raw,但您可以省略 -Raw 以使其在 PSv2 中也能工作(效率较低)):

    Get-ChildItem . *.xml -Recurse |
      ForEach-Object { 
        $filePath = $_.FullName 
        (Get-Content -Raw $filePath) -replace '&# 8211;', '–' `
           -replace '&# 160;', ' ' `
              -replace '&# 8221;', '”' |
                Set-Content -NoNewline $filePath
      }
    

    选读:

    TheMadTechnician 指出,在 ForEach-Object 调用的脚本块中定义变量 $filePath 以引用手头输入文件的完整路径的替代方法是使用 common参数-PipelineVariable(-pv):

    Get-ChildItem . *.xml -Recurse -PipelineVariable ThisFile |
      ForEach-Object { 
        (Get-Content -Raw $ThisFile.FullName) -replace '&# 8211;', '–' `
           -replace '&# 160;', ' ' `
              -replace '&# 8221;', '”' |
                Set-Content -NoNewline $ThisFile.FullName
      }
    

    注意传递给PipelinVariable的参数必须$前缀,因为它是要绑定的变量的名称
    @然后 987654343@ 指的是 Get-ChildItem 在所有后续管道段中的当前输出对象。

    虽然在这种特殊情况下没有太多收获,但使用
    -PipelinVariable 的一般优势在于,以这种方式绑定的变量可以在任何后续管道段中引用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-30
      • 2013-11-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多