[英]Windows batch or powershell. Replace “{\n}” text
我有一個包含以下內容的文本文件:
title
{
}
我需要用“mytext”替換{\\ n}。
我試着用這個:
powershell -Command "(gc file.txt) -replace \"{\n}\", "mytext"
沒有成功。
誰能幫助我? 謝謝。
為了-replace
跨線運行,必須將整個文件讀入內存作為單個字符串 ,這是Get-Content -Raw
( gc -raw
)確實(PSv3 +)。
此外,要考慮Windows上典型的CRLF( \\r\\n
)行結尾,請使用\\r?\\n
來匹配它們和僅LF( \\n
)行結尾,正如Mathias R. Jessen所建議的那樣。
隨着對引用的更正和簡化,我們得到:
powershell -Command "(gc -raw file.txt) -replace '\{\r?\n\}', 'mytext'"
請查看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
文本文件包含:
title
{
}
目標:將{\\ n}替換為“mytext”。
OP試圖:
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 here}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.