繁体   English   中英

Powershell如何在某些字符串后添加新行

[英]Powershell how to add new line after certain string

我是脚本新手。 我正在尝试解决一个问题,当时我正在查看Windows批处理和Powershell。 我发现了这个,但我不知道为什么它不起作用:

我有具有以下内容的input.txt文件:

<a> TEXT </a>
<c> text asdrtlj </c>
<a> another text </a>

我想在每个<a>之前添加新行,所以我尝试了以下操作:

powershell -Command "(gc input.txt) -replace '<a>', '`r`n<a>' | Out-File output.txt"

那添加换行符不起作用。 你能帮我吗?

PS:在搜索解决方案时,我发现了很多复杂的代码,但我还不了解它们,因此,如果您向我推荐一些不错的教程,从这里开始使用这种语言,我将非常感谢。

这里有几个问题。 由于<>字符,通过powershell的-command开关执行命令会导致一些保留字符问题。

而是打开PowerShell.exe窗口(开始->运行-> powershell)并直接执行命令。

您还需要使用双引号而不是单引号,以使诸如r和n的特殊代码起作用。 同样,`n应该足够:

(gc input.txt) -replace '<a>', "`n<a>" | Out-File output.txt

我们需要更多的引号。

powershell.exe -command "(gc 1_105.jpg) -replace '<a>', """"`r`n<a>""""|Out-File output.txt"

或小型重构怎么样?

powershell.exe -Command "gc input.txt|%{$_.replace('<a>',[environment]::newline+'<a>')}|Out-File output.txt"

暂无
暂无

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

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