如何通过只知道行的一部分来替换文本文件中的整行? [英] How to replace an entire line in text file by only knowing a portion of the line?

查看:54
本文介绍了如何通过只知道行的一部分来替换文本文件中的整行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本文件,其中包含类似于

I have a text file that contains a like that is similar to

设置金额 ="01:00:00"

我知道如何替换该行,但我目前的问题是,如果我知道该行的确切内容,我只能替换整行 - 使用 -match-替换.但是,有没有一种方法可以让我只搜索 Settings amount = 然后用我的新设置替换整行?这样无论当前值是多少,我都有能力扫描并赋予它不同的值.

I know how to replace the line but my issue is at the moment I am only able to replace the entire line if I know the exact contents of the line- using -match and -replace. However, is there a way that I can search for just Settings amount = and then just replace that entire line with my new setting? That way no matter what the current value is I have the power to scan and give it a different value.

这是我目前拥有的.

$DesiredTime = 'Settings amount="06:00:00" />'

$path = "C:\Windows\File.txt" 
 (Get-Content $path) -replace 'Settings amount="01:00:00" />', $DesiredTime | out-file $path

<小时>

有什么想法吗?


Any ideas?

推荐答案

看看 选择字符串.它将允许您找到包含您要查找的内容的整行.然后您可以更新该行.

Take a look at Select-String. It will allow you to find the entire line that contains what you are looking for. Then you can update the line.

这是一个示例文件

apple = yummy
bananna = yummy
pear = awful
grapes = divine

说我想替换包含梨"的行.先拿到行:

Say I want to replace the line containing "pear". First get the line:

$line = Get-Content c:\temp\test.txt | Select-String pear | Select-Object -ExpandProperty Line

现在我们只需读入内容并将该行替换为我们的行:

Now we just read in the content and replace the line with our line:

$content = Get-Content c:\temp\test.txt
$content | ForEach-Object {$_ -replace $line,"pear = amazing"} | Set-Content c:\temp\test.txt

确认更改

Get-Content C:\temp\test.txt
apple = yummy
bananna = yummy
pear = amazing
grapes = divine

请注意,如果您使用的是 XML,您可以将文档作为 XML 文档打开并简单地替换属性.如果没有看到源文件的样本,就很难判断.

Note that if you are working with XML, which it looks like you might be you can open the document as an XML document and simply replace the attribute. Without seeing a sample of your source file its hard to tell.

这篇关于如何通过只知道行的一部分来替换文本文件中的整行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆