首页 > 解决方案 > 使用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命令不返回任何内容(不是假的,只是什么都没有),所以我猜问题是找到匹配项而不是替换它。Win10下文件为UTF-8。

对于那些熟悉 zabbix 的人的免责声明,我知道我可以简单地在 EOF 中添加文本以获得相同的结果,但我喜欢我的配置文件组织得很好,所以我在这里打破了这个问题;)

那么为了查找和替换那段文本,我在这里遗漏了什么或做错了什么?谢谢

标签: powershell

解决方案


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

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

运算符使用正-replace则表达式匹配来查找文本。这意味着您必须在文本中考虑特殊的正则表达式字符并相应地处理它们。您可以单独转义它们,\也可以使用[regex]::Escape($searchedText)转义整个搜索字符串。


推荐阅读