如何用matlab实现文件中的单词替换,如何使用PowerShell查找和替换文本文件中的单词?...

要在PowerShell中搜索单词并将其替换到文件中,我们将使用字符串操作。实际上,PowerShell中的Get-Content命令用于读取几乎任何类型的文件内容。在本文中,我们正在考虑一个文本文件,如下所示。Get-Content C:\Temp\TestFile.txt

输出结果PS C:\> Get-Content C:\Temp\TestFile.txt

# In case of linux, networkInterface names are of the form eth*

# In Windows, please use the network full name from Device Manager

networkInterfaces: ["Microsoft Hyper-V Network Adapter"

]

overrideMetricsUsingScriptFile: false

scriptTimeoutInSec: 60

scriptFiles:

- osType: windows

filePath: monitors/NetworkMonitor/scripts/windows-metrics.bat

- osType: unixBase

filePath: monitors/NetworkMonitor/scripts/unix-base-metrics.sh

上面的输出是文件的内容,我们将使用它。我们需要找到NetWorkMonitor单词并将其替换为“活动”。请注意,上面的文件是文本文件,因此我们不需要将其转换为字符串,但是如果有其他扩展名,则可能需要在使用.ToString()命令或Out-String方法之前将输出转换为字符串执行任何操作。

现在,我们将首先找到请求的字符串,然后让我们检查一下需要使用Select-String cmdlet替换多少行。(Get-Content C:\Temp\TestFile.txt) | Select-String -Pattern "NetworkMonitor"

输出结果PS C:\> (Get-Content C:\Temp\TestFile.txt) | Select-String -Pattern "NetworkMonitor"

filePath: monitors/NetworkMonitor/scripts/windows-metrics.bat

filePath: monitors/NetworkMonitor/scripts/unix-base-metrics.sh

我们发现有两行带有“ NetworkMonitor”字样。我们需要用以下命令替换该单词。您还可以将Get-Content输出存储在变量中并对其执行操作。(Get-Content C:\Temp\TestFile.txt) -replace "NetworkMonitor","Active"

输出结果PS C:\> (Get-Content C:\Temp\TestFile.txt) -replace "NetworkMonitor","Active"

# In case of linux, networkInterface names are of the form eth*

# In Windows, please use the network full name from Device Manager

networkInterfaces: ["Microsoft Hyper-V Network Adapter"

]

overrideMetricsUsingScriptFile: false

scriptTimeoutInSec: 60

scriptFiles:

- osType: windows

filePath: monitors/Active/scripts/windows-metrics.bat

- osType: unixBase

filePath: monitors/Active/scripts/unix-base-metrics.sh

上面的命令替换了文件内容,但尚未存储,因此要保存更新的文件,我们将使用Set-Content,最终代码为,(Get-Content C:\Temp\TestFile.txt) -replace "NetworkMonitor","Active" | Set-Content

C:\Temp\Testfile.txt -Verbos

您也可以选择其他路径来保存文件。如果文件是只读的,则将-Force参数与Set-Content cmdlet一起使用。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值