温馨提示:本文翻译自stackoverflow.com,查看原文请点击:其他 - Replacing a block of text in a text file using powershell
powershell

其他 - 使用Powershell替换文本文件中的文本块

发布于 2020-03-27 11:25:55

好的,在将其标记为重复之前,我已经在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

So here I'm looking for that paragraph of text to replace it by this other paragraph of text to basically add a line in the right place but for some reason this does not work. I've tried adding various EOL characters as suggested in other posts but to no avail. I've seen other post suggesting to loop each line of the file but that doesn't seem optimal in the context. Also, the Select-String $searchedText -Path $pathConf command doesn't return anything (not false, just nothing) so I'm guessing the problem is finding the match rather than replacing it. The file is UTF-8 under Win10.

Disclaimer for those familiar with zabbix, I know I can simply add the text at the EOF for the same results but I like my config files well organized so here I am breaking my head over this problem ;)

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

查看更多

查看更多

提问者
JulioQc
被浏览
171
AdminOfThings 2019-07-03 23:27

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

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

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