powershell - 为什么在PowerShell的Get-Content,Regex和Set-Content之后都没有换行符?

标签 powershell newline

我想将文件模板加载到变量中,修改变量中的数据,然后将修改后的模板从变量输出到新位置。

问题是PowerShell正在从我的模板中删除换行符。

输入文件(模板文件)具有Unix行尾,输出也是必需的,因为修改后的版本的接收者是基于Unix的系统。

我有以下代码可以生成一个简明的一行:

[String] $replacement = "Foo Bar"
[String] $template = Get-Content -Path "$pwd\template.sh" -Encoding UTF8
$template = $template -replace '<REPLACE_ME>', $replacement
$template | Set-Content -Path "$pwd\script.sh" -Encoding UTF8

具有模板输入:
#!/bin/sh
myvar="<REPLACE_ME>"
echo "my variable: $myvar"
exit 0

结果为:
#!/bin/sh myvar="Foo Bar" echo "my variable: $myvar" exit 0

在我看来,在LF某处被一个简单的空白所代替。最后,在脚本末尾,添加了CR LF,该文件在模板文件中不存在。

如何保留行尾并防止在最终脚本中进一步添加(CR LF)错误的行尾?

最佳答案

对于$replacement变量,您实际上并不需要指定[string]类型,PowerShell将从分配中推断出该类型。

对于$template变量,[string]实际上是错误的。默认情况下,Get-Content将为您提供一个字符串数组(即行),而不是一个字符串。

但是实际上,您甚至根本不想将输入分成几行。当Set-ContentOut-File将数组视为输入时,它们将以空格连接。

使用-Raw会使Get-Content以一个字符串的形式返回整个文件,这样行尾(例如Linux文件的LF)也将保持原样。

$replacement = "Foo Bar"
$template = Get-Content -Path "$pwd\template.sh" -Encoding UTF8 -Raw
$template = $template -replace '<REPLACE_ME>', $replacement
Set-Content -Path "$pwd\script.sh" -Value $template -Encoding UTF8

PowerShell将使用BOM保存所有UTF-8文件。如果您不希望这样做,则必须使用其他实用程序来写入文件:
$UTF8_NO_BOM = New-Object System.Text.UTF8Encoding $False

$replacement = "Foo Bar"
$template = Get-Content -Path "$pwd\template.sh" -Encoding UTF8 -Raw
$template = $template -replace '<REPLACE_ME>', $replacement
[System.IO.File]::WriteAllText("$pwd\script.sh", $template, $UTF8_NO_BOM)

笔记:
  • PowerShell运算符(例如-replace)对数组进行静默操作。 $x -replace "search", "replacement"将对$ x的每个成员执行替换操作,无论是单个字符串还是它们的数组。
  • 推荐阅读:PowerShell Set-Content and Out-File what is the difference?
  • 关于powershell - 为什么在PowerShell的Get-Content,Regex和Set-Content之后都没有换行符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47512603/

    相关文章:

    powershell - 如何将文件类型与 powershell 脚本相关联?

    windows - 为什么 Windows 10 Enterprise Shell Launcher 出现黑屏?

    powershell - 未找到 Azure 服务器场

    PowerShell:从文本文件中读取行,构造源文件名和目标文件名,然后复制文件

    android - 从字符串中删除换行符

    notepad++ - 当/r/n 在文本中时,如何让 Notepad++ 显示单独的行?

    powershell - 用户及其所在的主机的Powershell列表

    javascript - 网页会自己创建换行符吗?

    string - 如何在多行中打破 YAML 中的字符串?

    字符串中的 Android 返回行 (\n)