[玩转系统] PowerShell 替换文件中的字符串 [4 种方法]
作者:精品下载站 日期:2024-12-14 05:30:33 浏览:17 分类:玩电脑
PowerShell 替换文件中的字符串 [4 种方法]
使用 -replace
运算符
要替换文本文件中的字符串:
- 使用
Get-Content
cmdlet 读取文本文件的内容。 - 使用
-replace
运算符将给定文本文件中的旧字符串替换为新字符串。 - 使用
Set-Content
cmdlet 将修改的内容写入文本文件。
文件.txt的内容:
This is a sample string.
使用 -replace 运算符:
$oldStr = "sample"
$newStr = "test"
$filePath = "E:\Test\file.txt"
$fileContent = Get-Content $filePath
Write-Host "Old File Content:`n$fileContent"
$newFileContent = $fileContent -replace $oldStr, $newStr
Set-Content $filePath $newFileContent
$fileContent = Get-Content $filePath
Write-Host "New File Content:`n$fileContent"
输出 :
Old File Content:
This is a sample string.
New File Content:
This is a test string.
首先,我们定义了两个名为 $oldStr
和 $newStr
的变量,其中包含 "sample"
和 "test"
字符串价值观;在这里,我们想用 file.txt
文件中的“test”
字符串替换“sample”
。然后,我们将 file.txt
文件的路径存储在 $filePath
变量中,我们将使用该变量来获取和设置内容。
因此,我们使用 Get-Content
cmdlet 检索给定位置处的项目的全部内容,即 $filePath
处的 file.txt
> 在上面的代码中。然后,我们将检索到的内容存储在 $fileContent
变量中。请记住,Get-Content
cmdlet 一次读取一行文件并返回一组对象,每个对象都对应于该行内容。然后,我们使用 Write-Host
cmdlet 在 PowerShell 控制台上打印 $fileContent
。
现在,我们使用 -replace
运算符将 $fileContent
中的 $oldStr
替换为 $newStr
并存储$newFileContent
变量中的更新内容,进一步与 Set-Content
cmdlet 一起使用以将 $newFileContent
写入 文件中.txt
文件位于 $filePath
。
同样,我们使用 Get-Content
读取指定 $filePath
处的文件,将检索到的内容存储在 $fileContent
变量中,并使用它与 Write-Host
cmdlet 一起在 PowerShell 控制台上显示更新的内容。当然,我们可以通过手动打开file.txt
来查看更新的内容,但使用Get-Content
是在控制台上查看更新内容的更方便的方法。
让我们看另一个例子来了解 -replace
运算符默认情况下是否不区分大小写。
文件.txt的内容:
This is a sample string.
使用 -replace 运算符:
$oldStr = "Sample"
$newStr = "test"
$filePath = "E:\Test\file.txt"
$fileContent = Get-Content $filePath
Write-Host "Old File Content:`n$fileContent"
$newFileContent = $fileContent -replace $oldStr, $newStr
Set-Content $filePath $newFileContent
$fileContent = Get-Content $filePath
Write-Host "New File Content:`n$fileContent"
输出 :
Old File Content:
This is a sample string.
New File Content:
This is a test string.
首先看上面提供的文件内容;我们在 file.txt
中有一个 sample
字符串。但是,考虑到上面的代码片段,我们搜索了 Sample
字符串以将其替换为 test
,并且 -replace
运算符做到了;请参阅上面的输出。由此证明,-replace 运算符默认不区分大小写,这意味着它的 sample
和 Sample
是相同的字符串。
我们也可以使用 replace
和 -ireplace
运算符,因为它们都用旧字符串替换提供的新字符串,并且不区分大小写。
如果我们在替换时必须注意区分大小写,我们可以使用 -creplace 运算符;请参见以下示例。
文件.txt的内容:
This is a sample string.
使用 -creplace 运算符:
$oldStr = "Sample"
$newStr = "test"
$filePath = "E:\Test\file.txt"
$fileContent = Get-Content $filePath
Write-Host "Old File Content:`n$fileContent"
$newFileContent = $fileContent -creplace $oldStr, $newStr
Set-Content $filePath $newFileContent
$fileContent = Get-Content $filePath
Write-Host "New File Content:`n$fileContent"
输出 :
Old File Content:
This is a sample string.
New File Content:
This is a sample string.
观察上面的输出;即使使用 -creplace
运算符后,文件内容也没有发生任何更改。为什么?因为我们搜索了 Sample
,但该文件包含 sample
,这与 -creplace
运算符不同,因为它区分大小写默认情况下。
在 -replace
运算符前添加 i
和 c
作为 -ireplace
和 -creplace
用于不区分大小写和区分大小写的替换。请注意,-repalce
和 -ireplace
是不区分大小写的运算符。
让我们让这段代码变得更有趣,并在不丢失剩余内容的情况下替换 n
行中的字符串。请参阅以下代码片段来练习它。您可以使用 PowerShell 3.0 或更高版本成功运行以下代码。
使用 -replace
运算符替换 n
行中的字符串
要替换文本文件的 n
行中的字符串:
- 将
Get-Content
与-TotalCount
参数结合使用可读取前4
行。 - 使用
for
循环迭代读取的内容: 在每次迭代中:
- 使用
-replace
运算符将步骤1中读取内容的当前行中的旧字符串替换为新字符串
- 使用
Get-Content
与 -Tail
参数结合使用可读取最后 4
行。+=
运算符将修改的内容(前四行)与未更改的内容(后四行)连接起来。Set-Content
将内容写入文件的给定位置。使用 -replace 运算符替换 N 行中的字符串:
$oldStr = "sample"
$newStr = "test"
$filePath = "E:\Test\file.txt"
$numberOfLines = 4
$fileContent = Get-Content $filePath -TotalCount 4
for ($i = 0; $i -lt $numberOfLines; $i++) {
$fileContent[$i] = $fileContent[$i] -replace $oldStr, $newStr
}
$fileContent += Get-Content $filePath -Tail 4
Set-Content $filePath $fileContent
file.txt的旧内容:
This is a sample string1.
This is a sample string2.
This is a sample string3.
This is a sample string4.
This is a sample string5.
This is a sample string6.
This is a sample string7.
This is a sample string8.
file.txt的新内容:
This is a test string1.
This is a test string2.
This is a test string3.
This is a test string4.
This is a sample string5.
This is a sample string6.
This is a sample string7.
This is a sample string8.
此示例与前面的示例类似,但有一些修改。首先,我们定义了 $oldStr
、$newStr
、$filePath
和 $numberOfLines
来保存旧字符串、新字符串、文本文件的路径以及我们将读取的行数。
然后,我们使用带有 -TotalCount
参数的 Get-Content
cmdlet 从 file.txt
读取 4
行> 位于$filePath
;我们将检索到的内容存储在 $fileContent
变量中。
接下来,我们使用 for
循环来循环 $fileContent
的每一行。在每次迭代中,我们使用 []
表示的索引运算符来访问当前行(即 $fileContent[$i]
),使用 -replace
运算符将该行中的 $oldStr
替换为 $newStr
,并更新了 $fileContent
中的该特定行。
完成 for
循环后,我们使用 Get-Content
cmdlet 以及 -Tail
参数作为 Get-Content $filePath -Tail 4
从位于 $filePath
的文件中读取最后四行,我们使用 +=
将其与 $fileContent
连接起来代码> 运算符。最后,我们使用 Set-Content
cmdlet 将 $fileContent
写入 $filePath
处的文件。您可以观察上面file.txt
的新旧内容。
同样,我们可以替换最后 4 行中的字符串。
使用 -replace 运算符替换 N 行中的字符串:
$oldStr = "sample"
$newStr = "test"
$filePath = "E:\Test\file.txt"
$numberOfLines = 4
$fileContent = Get-Content $filePath -Tail 4
for ($i = 0; $i -lt $numberOfLines; $i++) {
$fileContent[$i] = $fileContent[$i] -replace $oldStr, $newStr
}
$head = Get-Content $filePath -Head 4
$head += $fileContent
Set-Content $filePath $head
file.txt的旧内容:
This is a sample string1.
This is a sample string2.
This is a sample string3.
This is a sample string4.
This is a sample string5.
This is a sample string6.
This is a sample string7.
This is a sample string8.
file.txt的新内容:
This is a sample string1.
This is a sample string2.
This is a sample string3.
This is a sample string4.
This is a test string5.
This is a test string6.
This is a test string7.
This is a test string8.
您在指定要执行替换操作的文件名时是否有拼写错误?在这种情况下,您将找不到需要替换的字符串。因此,我们必须有条件来检查文件是否具有所需的字符串。如果是,请更换;否则,让用户知道。请参阅以下示例。
使用 -replace 运算符替换 N 行中的字符串:
$oldStr = "samples"
$newStr = "test"
$filePath = "E:\Test\file.txt"
$numberOfLines = 4
$check = Select-String -pattern $oldStr -path $filePath
if($check -eq $null){
Write-output "String Not Found"
}
else{
$fileContent = Get-Content $filePath -Tail 4
for ($i = 0; $i -lt $numberOfLines; $i++) {
$fileContent[$i] = $fileContent[$i] -replace $oldStr, $newStr
}
$head = Get-Content $filePath -Head 4
$head += $fileContent
Set-Content $filePath $head
}
输出 :
String Not Found
我们收到一条输出消息,指出未找到指定的字符串,因为 file.txt
包含 sample
,而不是 samples
。那么我们是如何识别的呢?我们使用 Select-String
并将 -pattern
和 -path
参数设置为 $oldStr
和 $filePath
。如果未找到指定的模式(我们将其存储在 $check
变量中),则此 cmdlet 将返回 $null
。
此外,我们使用 if
语句和 -eq
运算符来检查 $check
是否等于 $null
。如果是,则打印 String Not Found
;否则,跳转到else
块并进行替换操作。我们如何更换它?前面的示例中已经介绍过它。
使用 Replace()
方法
要使用 PowerShell 替换给定文本文件中的字符串:
- 使用
Select-String
cmdlet 检查给定文件中是否存在指定的模式。然后,将返回值存储在变量中。 - 将
-if
与-eq
运算符结合使用来检查变量的值(在步骤 1 中创建)是否等于null
。 - 如果是,则使用
Write-Host
显示消息并退出;否则,跳转到else
块。 在
else
块中:- 使用
Get-Content
读取给定路径的文件内容。
- 使用
- 使用
Replace()
方法将上一步读取的内容中的旧字符串替换为新字符串。 - 使用
Set-Content
将修改的内容写入给定文件中。
使用 Replace() 方法:
$oldStr = "sample"
$newStr = "test"
$filePath = "E:\Test\file.txt"
$check = Select-String -pattern $oldStr -path $filePath
if($check -eq $null){
Write-output "String Not Found"
}
else{
$fileContent = Get-Content $filePath
$newFileContent = $fileContent.Replace($oldStr, $newStr)
Set-Content $filePath $newFileContent
}
file.txt 文件的旧内容:
This is a sample string1.
This is a sample string2.
This is a sample string3.
This is a sample string4.
This is a sample string5.
This is a sample string6.
This is a sample string7.
This is a sample string8.
file.txt 文件的新内容:
This is a test string1.
This is a test string2.
This is a test string3.
This is a test string4.
This is a test string5.
This is a test string6.
This is a test string7.
This is a test string8.
此示例与上一节中学习的示例类似,但这次我们使用了 Replace()
方法。它还查找指定的字符串并将其替换为文件中的另一个给定字符串。但是,它本质上是区分大小写的;为此,Sample
和 sample
是两个不同的字符串。
使用 StreamReader
/StreamWriter
和 File
类
要使用 PowerShell 替换给定文本文件中的字符串:
- 使用
Select-String
cmdlet 检查指定文本文件中是否存在给定模式。然后,将返回值存储在变量中。 - 将
-if
与-eq
运算符结合使用来检查变量的值(在步骤 1 中创建)是否等于null
。 - 如果是,则使用
Write-Host
显示消息并退出;否则,跳转到else
块。 在
else
块中:- 使用
new()
方法创建StreamReader
类的对象。
- 使用
- 使用
ReadToEnd()
读取指定文本文件的全部内容。 - 使用
Close()
方法关闭StreamdReader
类的实例。 - 使用
-replace
运算符将旧字符串替换为新字符串。 - 使用
StreamWriter
类的new()
方法创建其对象。 - 使用
Write()
方法写入更新的内容。 - 使用
Close()
方法关闭StreamWriter
类的实例。
使用 StreamReader 和 StreamWriter 类:
$oldStr = "sample"
$newStr = "test"
$filePath = "E:\Test\file.txt"
$check = Select-String -pattern $oldStr -path $filePath
if($check -eq $null){
Write-output "String Not Found"
}
else{
$streamReader = [System.IO.StreamReader]::new($filePath)
$fileContent = $streamReader.ReadToEnd()
$streamReader.Close()
$fileContent = $fileContent -replace $oldStr, $newStr
$streamWriter = [System.IO.StreamWriter]::new($filePath)
$streamWriter.Write($fileContent)
$streamWriter.Close()
}
file.txt 文件的旧内容:
This is a sample string1.
This is a sample string2.
This is a sample string3.
This is a sample string4.
This is a sample string5.
This is a sample string6.
This is a sample string7.
This is a sample string8.
file.txt 文件的新内容:
This is a test string1.
This is a test string2.
This is a test string3.
This is a test string4.
This is a test string5.
This is a test string6.
This is a test string7.
This is a test string8.
我们已经了解了定义的变量、代码流和条件。在这里,我们使用 StreamReader
类读取文本文件,并使用 StreamWriter
类写入文本文件。
同样,我们可以使用System.IO
命名空间的File
类;它比 StreamReader
和 StreamWriter
类更加优化。请参阅以下示例。
使用文件类:
$oldStr = "sample"
$newStr = "test"
$filePath = "E:\Test\file.txt"
$check = Select-String -pattern $oldStr -path $filePath
if($check -eq $null){
Write-output "String Not Found"
}
else{
$fileContent = [System.IO.File]::ReadAllText($filePath)
$fileContent = $fileContent -replace $oldStr, $newStr
[System.IO.File]::WriteAllText($filePath, $fileContent)
}
file.txt 文件的旧内容:
This is a sample string1.
This is a sample string2.
This is a sample string3.
This is a sample string4.
This is a sample string5.
This is a sample string6.
This is a sample string7.
This is a sample string8.
file.txt 文件的新内容:
This is a test string1.
This is a test string2.
This is a test string3.
This is a test string4.
This is a test string5.
This is a test string6.
This is a test string7.
This is a test string8.
本节中的两个解决方案都执行不区分大小写的替换,因为我们使用了 -replace
运算符,默认情况下该运算符不区分大小写。
使用管道替换所有出现的情况
如果您需要替换给定文本文件中所有出现的指定字符串,建议使用管道,因为它是单行解决方案。
将管道与 -replace 运算符一起使用:
(Get-Content "E:\Test\file.txt") -replace "sample", "test" |
Set-Content "E:\Test\file.txt"
file.txt 文件的旧内容:
This is a sample string1.
This is a sample string2.
This is a sample string3.
This is a sample string4.
This is a sample string5.
This is a sample string6.
This is a sample string7.
This is a sample string8.
file.txt 文件的新内容:
This is a test string1.
This is a test string2.
This is a test string3.
This is a test string4.
This is a test string5.
This is a test string6.
This is a test string7.
This is a test string8.
我们已经了解了所使用的 cmdlet 和运算符。新事物是管道,我们用它来将数据从前一个进程转发到下一个进程。在上面的代码中,|
表示的管道将读取内容的字符串替换为写入给定文件中的 Set-Content
cmdlet 后转发检索到的数据。
如果您使用此方法,请不要忘记将 Get-Content "E:\Test\file.txt"
括在 ()
内;否则,将一次读取一行内容并沿着管道流动,直到到达 Set-Content
cmdlet。这样,它将尝试写入已由 Get-Content
打开的同一文件,并且您将收到错误。
这就是替换文件中的字符串的全部内容。
猜你还喜欢
- 03-30 [玩转系统] 如何用批处理实现关机,注销,重启和锁定计算机
- 02-14 [系统故障] Win10下报错:该文件没有与之关联的应用来执行该操作
- 01-07 [系统问题] Win10--解决锁屏后会断网的问题
- 01-02 [系统技巧] Windows系统如何关闭防火墙保姆式教程,超详细
- 12-15 [玩转系统] 如何在 Windows 10 和 11 上允许多个 RDP 会话
- 12-15 [玩转系统] 查找 Exchange/Microsoft 365 中不活动(未使用)的通讯组列表
- 12-15 [玩转系统] 如何在 Windows 上安装远程服务器管理工具 (RSAT)
- 12-15 [玩转系统] 如何在 Windows 上重置组策略设置
- 12-15 [玩转系统] 如何获取计算机上的本地管理员列表?
- 12-15 [玩转系统] 在 Visual Studio Code 中连接到 MS SQL Server 数据库
- 12-15 [玩转系统] 如何降级 Windows Server 版本或许可证
- 12-15 [玩转系统] 如何允许非管理员用户在 Windows 中启动/停止服务
取消回复欢迎 你 发表评论:
- 精品推荐!
-
- 最新文章
- 热门文章
- 热评文章
[影视] 黑道中人 Alto Knights(2025)剧情 犯罪 历史 电影
[古装剧] [七侠五义][全75集][WEB-MP4/76G][国语无字][1080P][焦恩俊经典]
[实用软件] 虚拟手机号 电话 验证码 注册
[电视剧] 安眠书店/你 第五季 You Season 5 (2025) 【全10集】
[电视剧] 棋士(2025) 4K 1080P【全22集】悬疑 犯罪 王宝强 陈明昊
[软件合集] 25年6月5日 精选软件22个
[软件合集] 25年6月4日 精选软件36个
[短剧] 2025年06月04日 精选+付费短剧推荐33部
[短剧] 2025年06月03日 精选+付费短剧推荐25部
[软件合集] 25年6月3日 精选软件44个
[剧集] [央视][笑傲江湖][2001][DVD-RMVB][高清][40集全]李亚鹏、许晴、苗乙乙
[电视剧] 欢乐颂.5部全 (2016-2024)
[电视剧] [突围] [45集全] [WEB-MP4/每集1.5GB] [国语/内嵌中文字幕] [4K-2160P] [无水印]
[影视] 【稀有资源】香港老片 艺坛照妖镜之96应召名册 (1996)
[剧集] 神经风云(2023)(完结).4K
[剧集] [BT] [TVB] [黑夜彩虹(2003)] [全21集] [粤语中字] [TV-RMVB]
[实用软件] 虚拟手机号 电话 验证码 注册
[资源] B站充电视频合集,包含多位重量级up主,全是大佬真金白银买来的~【99GB】
[影视] 内地绝版高清录像带 [mpg]
[书籍] 古今奇书禁书三教九流资料大合集 猎奇必备珍藏资源PDF版 1.14G
[电视剧] [突围] [45集全] [WEB-MP4/每集1.5GB] [国语/内嵌中文字幕] [4K-2160P] [无水印]
[剧集] [央视][笑傲江湖][2001][DVD-RMVB][高清][40集全]李亚鹏、许晴、苗乙乙
[电影] 美国队长4 4K原盘REMUX 杜比视界 内封简繁英双语字幕 49G
[电影] 死神来了(1-6)大合集!
[软件合集] 25年05月13日 精选软件16个
[精品软件] 25年05月15日 精选软件18个
[绝版资源] 南与北 第1-2季 合集 North and South (1985) /美国/豆瓣: 8.8[1080P][中文字幕]
[软件] 25年05月14日 精选软件57个
[短剧] 2025年05月14日 精选+付费短剧推荐39部
[短剧] 2025年05月15日 精选+付费短剧推荐36部
- 最新评论
-
- 热门tag