当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] PowerShell 替换文件中的字符串 [4 种方法]

作者:精品下载站 日期:2024-12-14 05:30:33 浏览:17 分类:玩电脑

PowerShell 替换文件中的字符串 [4 种方法]


[玩转系统] 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 运算符默认不区分大小写,这意味着它的 sampleSample 是相同的字符串。

我们也可以使用 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 运算符前添加 ic 作为 -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() 方法。它还查找指定的字符串并将其替换为文件中的另一个给定字符串。但是,它本质上是区分大小写的;为此,Samplesample 是两个不同的字符串。

    使用 StreamReader/StreamWriterFile

    要使用 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类;它比 StreamReaderStreamWriter 类更加优化。请参阅以下示例。

    使用文件类:

    $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 打开的同一文件,并且您将收到错误。

    这就是替换文件中的字符串的全部内容。

    您需要 登录账户 后才能发表评论

    取消回复欢迎 发表评论:

    关灯