Prevent trailing newline in PowerShell Out-File command
如何防止PowerShell的Out-File命令在输出的文本后添加换行符?
例如,运行以下命令将生成一个内容为" TestTest r n"的文件,而不仅仅是" TestTest"。
1 | "TestTest" | Out-File -encoding ascii test.txt |
在PowerShell 5.0+中,您将使用:
1 | "TestTest" | Out-File -encoding ascii test.txt -NoNewline |
但是在早期版本中,您根本无法使用该cmdlet。
尝试这个:
1 | [System.IO.File]::WriteAllText($FilePath,"TestTest",[System.Text.Encoding]::ASCII) |
为了补充briantist的有用答案,请重新输入
以下内容不仅适用于
请注意,
换句话说:输入对象的字符串表示形式直接连接在一起,没有分隔符(终止符)。
因此,以下命令导致相同的文件内容(
1 2 3 4 5 | # Single input string "TestTest" | Out-File -encoding ascii test.txt -NoNewline # Equivalent command: 2-element array of strings that are directly concatenated. "Test","Test" | Out-File -encoding ascii test.txt -NoNewline |
为了仅在输出对象之间而不是之后放置换行符,必须将对象与换行符明确地连接起来:
1 | "Test","Test" -join"`r`n" | Out-File -encoding ascii test.txt -NoNewline |
要创建Unix风格的仅LF换行符,请使用
警告:
上面的
如果您的输入仅包含
有关
如果您的输入包含要格式化的非字符串,就像要打印到控制台一样,则实际上没有简单的解决方案:虽然您可以使用