我有一个文本文件,其中包含:
title
{
}
我需要将{\n}替换为"mytext“。
我试着使用这个:
powershell -Command "(gc file.txt) -replace \"{\n}\", "mytext"
但没有成功。
有人能帮帮我吗?谢谢。
发布于 2018-04-19 00:51:39
-replace
跨行运行,您必须将整个文件作为单个字符串读取到内存中,这是Get-Content -Raw
(gc -raw
)执行的操作。要说明Windows上典型的CRLF (\r\n
)行尾,请按照Mathias R. Jessen的建议,使用\r?\n
来匹配它们和仅LF (\n
)行尾。除了对报价进行更正和简化之外,我们还可以获得:
powershell -Command "(gc -raw file.txt) -replace '\{\r?\n\}', 'mytext'"
发布于 2018-04-19 00:35:33
请查看mklement0对此问题的答案,因为我的答案不起作用。我将把它作为文字字符串替换的方法留在这里。
在PowerShell控制台中尝试一下。如果它可以工作,您可以始终将其作为脚本保存在.ps1文件中。
$FilePath = "\\Server\Share\PathToFile\File.txt"
$ToBeReplaced = "{\n}"
$ReplaceWith = "mytext"
$File = Get-Content $FilePath
$File | foreach { $_.Replace($ToBeReplaced,$ReplaceWith) } | Set-Content $FilePath
发布于 2018-04-19 13:14:43
包含以下内容的文本文件:
title
{
}
目标:将{\n}替换为mytext。
尝试的操作:
powershell -Command "(gc file.txt) -replace \"{\n}\", "mytext"
首先,Get-Content不会返回NewLines (默认情况下),而是返回换行符分隔的字符串数组,因此这是您尝试的命令的最直接转换:
(Get-Content file.txt) -join 'mytext'
或者使用-Raw防止Get-Content拆分,只返回一个字符串:
(get-content -raw .\PSRLKeyBindings.txt) -replace '\n', 'mytext'
这在不使用正则表达式、多行修饰符等的情况下也可以工作(在我测试之前,我一直不确定是否会这样)。
如果你真的想从某个任意的地方运行它(cmd.exe,运行对话框,从快捷方式调用),那么你需要"powershell -command“,但如果你只是从PowerShell控制台运行它,那么你可以省略上面的内容。
下面是“启动PowerShell版本--尽管我使用的是-noprofile,因为我的大量配置文件需要大约10秒来初始化:
powershell -noprofile -Command "(get-content -first 10 .\PSRLKeyBindings.txt) -join 'mytext'"
在“命令参数”中使用引号是必要的--或者你可以用大括号把它括起来{ -command { command here }
https://stackoverflow.com/questions/49904712
复制相似问题