我正在尝试编写一个Windows批处理文件,它将替换出现有角度的括号(> <),并在其间插入换行符。
我是PowerShell的新手,但在搜索可能的解决方案时,我发现PowerShell的以下工作:
(get-content input.txt) -replace "><", ">`n<" | set-content output.txt
要在Windows批处理中使用它,我需要将其包装在里面
powershell -command "arguments"
所以最后的命令是这样的:
powershell -command "(gc input.txt) -replace '><', '>`n<' | sc output.txt"
但是,这当然不起作用,因为替换文本周围的单引号会导致严重引用转义字符被字面处理。
我已经远程搜索了正确的转义字符组合,以便识别PowerShell转义字符并找到类似的答案in here,但是当我尝试这个建议时,我得到一个“<此时意外”错误。我认为我需要的更复杂,因为我的搜索字符串也包含有角度的括号。
查看powershell.exe命令行选项。您可以使用脚本块:
powershell -command {(gc input.txt) -replace "><", ">`n<" | sc output.txt}
避免使用转义字符和双引号?
powershell -command "(gc d:\t\input.txt) -replace '><', ('>'+[char]10+'<') | sc d:\t\output.txt"
我已经解决了这个问题。我也使用了延迟扩展,所以最后的命令是:
powershell -Command "(gc !inputfile!) -replace (\"^>^<\", \"^>`n^<\") | sc !outputfile!"
所以它实际上使用了三种不同类型的转义字符! \和^和`的组合。
我希望我可以说我在逻辑上做了它,但最后它只是在> <上使用不同转义的随机尝试。
但现在这是一个很好的参考,如何在Windows批处理中使用PowerShell而不使用单引号将转义字符转换为文字。