簡體   English   中英

使用Powershell替換文本文件中的文本塊

[英]Replacing a block of text in a text file using powershell

好的,在將其標記為重復之前,我已經在StackOverflow上的類似問題中嘗試了大多數建議,但是在我的情況下它們都沒有起作用,因此在此我尋求幫助。

首先,這是代碼摘錄:

$pathConf = "C:\Program Files (x86)\Zabbix Agent\zabbix_agentd.conf"

$searchedText = 
'### Option: Alias
#   Sets an alias for an item key. It can be used to substitute long and complex item key with a smaller and simpler one.
#   Multiple Alias parameters may be present. Multiple parameters with the same Alias key are not allowed.
#   Different Alias keys may reference the same item key.
#   For example, to retrieve paging file usage in percents from the server:
#   Alias=pg_usage:perf_counter[\Paging File(_Total)\% Usage]
#   Now shorthand key pg_usage may be used to retrieve data.
#   Aliases can be used in HostMetadataItem but not in HostnameItem or PerfCounter parameters.
#
# Mandatory: no
# Range:
# Default:'

$replacedText = 
'### Option: Alias
#   Sets an alias for an item key. It can be used to substitute long and complex item key with a smaller and simpler one.
#   Multiple Alias parameters may be present. Multiple parameters with the same Alias key are not allowed.
#   Different Alias keys may reference the same item key.
#   For example, to retrieve paging file usage in percents from the server:
#   Alias=pg_usage:perf_counter[\Paging File(_Total)\% Usage]
#   Now shorthand key pg_usage may be used to retrieve data.
#   Aliases can be used in HostMetadataItem but not in HostnameItem or PerfCounter parameters.
#
# Mandatory: no
# Range:
# Default:
Alias=my.service.discovery[*]:service.discovery'

((Get-Content -path $pathConf -raw) -replace $searchedText, $replacedText) | Set-Content -Path $pathConf

所以在這里,我正在尋找該文本段落,以將該文本段落替換為該文本的另一段落,以便基本上在正確的位置添加一行,但是由於某種原因,這行不通。 我嘗試添加其他帖子中建議的各種EOL字符,但無濟於事。 我看過另一篇文章建議循環文件的每一行,但這在上下文中似乎不是最佳的。 另外, Select-String $searchedText -Path $pathConf命令不會返回任何內容(不是false,什么也沒有),所以我猜問題出在尋找匹配項而不是替換匹配項。 該文件是Win10下的UTF-8。

對於熟悉zabbix的人免責聲明,我知道我可以直接在EOF上添加文本以獲得相同的結果,但是我喜歡配置文件井井有條,因此在這里我為解決這個問題而煩惱;)

那么,為了查找和替換該段文本,我在這里想念或做錯了什么? 謝謝

由於您只是用文本替換文字文本,因此可以使用String.Replace方法。

(Get-Content -path $pathConf -raw).Replace($searchedText,$replacedText)

-replace運算符使用正則表達式匹配來查找文本。 這意味着您將必須在文本中考慮特殊的正則表達式字符並進行相應處理。 您可以使用\\單獨對它們進行轉義,也可以使用[regex]::Escape($searchedText)對整個搜索字符串進行轉義。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM