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

[玩转系统] PowerShell 替换子字符串

作者:精品下载站 日期:2024-12-14 16:49:57 浏览:14 分类:玩电脑

PowerShell 替换子字符串


PowerShell String 存储字符串数据,并提供字符串操作和方法来替换字符串、替换字符串中的子字符串、替换字符等……

PowerShell 有一个 replace() 方法和 PowerShell 替换运算符 来替换字符串或字符。

在本文中,我们将讨论如何使用 PowerShell Replace() 方法和 PowerShell 替换运算符来替换字符串中的子字符串。

使用replace()方法替换PowerShell中的子字符串

让我们通过一个例子来了解PowerShell替换子字符串。

让我们考虑一下,我们有一个字符串存储在变量 $str 中,如下所示

$str = "Welcome! Admin to ShellGeek!"

我们希望将字符串中的子字符串 Admin 替换为字符串 ShellAdmin,以便输出字符串的值应为“Welcome! ShellAdmin 到 ShellGeek!

要在 PowerShell 中替换给定字符串中的子字符串,请使用 PowerShell replace() 方法。

$str.Replace("Admin","ShellAdmin")

在上面的 PowerShell 脚本中,我们通过 $str 变量调用 replace() 方法。它接受两个参数,例如查找“Admin”的字符串和替换为“ShellAdmin”的字符串

上述使用字符串中的替换子字符串的 PowerShell 脚本的输出为:

WelCome!  ShellAdmin to ShellGeek!

[玩转系统] PowerShell 替换子字符串

酷提示:如何使用 PowerShell 替换字符串中的多个字符!

使用替换运算符替换 PowerShell 中字符串中的子字符串

您可以使用PowerShell替换运算符来替换字符串中的子字符串。 PowerShell replace 运算符有两个与 replace() 方法类似的参数,例如要查找的字符串和要替换的字符串。

让我们考虑一个示例来了解替换运算符替换 PowerShell 字符串中的文本。

$str = "Welcome! Admin to ShellGeek!"

$str -replace "Admin","ShellAdmin" 

在上面的 PowerShell 脚本中,$str 变量存储字符串。为了替换字符串中的子字符串,我们使用了 PowerShell replace 运算符,并以逗号分隔的方式传递旧值和新值。

使用替换运算符替换字符串中的文本后,上述 PowerShell 脚本的输出为:

PS C:\> $str = "Welcome! Admin to ShellGeek!"                                                                           

PS C:\> $str -replace "Admin","ShellAdmin"                                                                              

Welcome! ShellAdmin to ShellGeek!

PS C:\>                                                                                                                                                                                                                                                      

结论

希望上面关于使用 PowerShell Replace() 方法和 PowerShell 替换运算符的 PowerShell 替换子字符串的文章对您有所帮助。

您可以在 ShellGeek 主页上找到有关 PowerShell Active Directory 命令和 PowerShell 基础知识的更多主题。

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

取消回复欢迎 发表评论:

关灯