[英]How do I get preceding and following lines when a specific string is contained in a line? (Python and deque())
[英]How Do I change a string in a specific line contained in a file preserving all other lines?
我有一個包含以下信息的文件:
Type=OleDll
Reference=*\G{00020430-0000-0000-C000-000000000046}#2.0#0#..\..\..\..\..\..\..\Windows\SysWOW64\stdole2.tlb#OLE Automation
Reference=*\G{7C0FFAB0-CD84-11D0-949A-00A0C91110ED}#1.0#0#..\..\..\..\..\..\..\Windows\SysWOW64\msdatsrc.tlb#Microsoft Data Source Interfaces for ActiveX Data Binding Type Library
Reference=*\G{26C4A893-1B44-4616-8684-8AC2FA6B0610}#1.0#0#..\..\..\..\..\..\..\Windows\SysWow64\Conexion_NF.dll#Zeus Data Access Library 1.0 (NF)
Reference=*\G{9668818B-3228-49FD-A809-8229CC8AA40F}#1.0#0#..\packages\ZeusMaestrosContabilidad.19.3.0\lib\native\ZeusMaestrosContabilidad190300.dll#Zeus Maestros Contables Des (Contabilidad)
我需要使用 powershell 更改第 5 行的 {} 字符之間的數據,並保存更改以保留文件中的所有其他信息。
試試正則表達式: (?<=(?:.*\n){4}Reference=\*\\G\{)[\w-]+
如果 {} 的內容始終相同,您可以這樣做:
(Get-Content $yourfile) -replace $regex, ('{9668818B-3228-49FD-A809-8229CC8AA40F}') | Set-Content $newValue;
一種解決方案:
$Content=Get-Content "C:\temp\test.txt"
$Row5Splited=$Content[4].Split("{}".ToCharArray())
$Content[4]="{0}{1}{2}" -f $Row5Splited[0], "{YOURNEWVALUE}", $Row5Splited[2]
$Content | Out-File "C:\temp\test2.txt"
一種方法是找到,
(.*Reference=\*\\G{)[^\r\n}]+
並替換為,
$1any_thing_you_like_to_replace_with
jex.im可視化正則表達式:
如果您想簡化/修改/探索表達式,它已在regex101.com的右上角面板上進行了解釋。 如果您願意,您還可以在此鏈接中觀看它如何與一些示例輸入匹配。
您可以使用-replace
運算符執行正則表達式匹配和字符串替換。
如果每行只有一對{}
,您可以執行以下操作 where .*?
盡可能少地匹配任何非換行符。 由於默認情況下Get-Content
創建一個 object 是一個行數組,因此您可以通過索引訪問每一行,其中[4]
為第 5 行。
$content = Get-Content File.txt
$content[4] = $content[4] -replace '{.*?}','{new data}'
$content | Set-Content File.txt
如果每行可能有多個{}
對,您將需要更具體地使用您的正則表達式。 一個積極的后向斷言(?<=)
就可以了。
$content = Get-Content File.txt
$content[4] = $content[4] -replace '(?<=Reference=\*\\G){.*?}','{newest data}'
$content | Set-Content File.txt
對於不知道哪一行包含要替換的數據的情況,您需要更具體地了解要替換的數據。
Get-Content File.txt -replace '{9668818B-3228-49FD-A809-8229CC8AA40F}','{New Data}' | Set-Content
如果有編碼要求,請考慮在Get-Content和Set-Content命令上使用-Encoding
參數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.