如何在 Windows PowerShell 中替换文本文件中表达式的一部分?

问题描述 投票:0回答:2

我对编码/PowerShell 完全陌生,很抱歉我无法自己解决这个问题。 我有一个包含约 250.000 行的文本文件 (lit.bib)。我想在表达式“{ extunderscore }”出现时将其替换为“_”,并将文件保存为“lit_t.bib”。例如,我想要这条线

doi = {10.1007/978-3-319-89999-2{ 扩展下划线}198}

改为

doi = {10.1007/978-3-319-89999-2_198}

我该怎么做?

(Get-Content lit.bib) -replace '{\textunderscore }', '_' | Out-File -encoding UTF8 lit_t.bib

谢谢!

powershell replace
2个回答
0
投票

使用

.Replace
代替
-replace
(区分大小写的方法)进行文字替换:

(Get-Content lit.bib -Raw).Replace('{\textunderscore }', '_') |
    Out-File -encoding UTF8 lit_t.bib

或者使用

-replace
转义正则表达式特殊字符(用于字面匹配):

(Get-Content lit.bib -Raw) -replace [regex]::Escape('{\textunderscore }'), '_' |
    Out-File -encoding UTF8 lit_t.bib

0
投票

要使用 PowerShell 将文本文件中的表达式“{ extunderscore }”替换为“_”,可以使用以下命令:

(Get-Content lit.bib) -replace '{\textunderscore }', '_' | Set-Content -Encoding utf8 lit_t.bib
© www.soinside.com 2019 - 2024. All rights reserved.