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

[玩转系统] 在 PowerShell 中用换行符替换空格

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

在 PowerShell 中用换行符替换空格


使用 PowerShell 字符串 replace() 方法或 replace 运算符将字符串中的空格替换为新行。例如$str.replace(" ","`r`n") 将空格替换为新行。

replace() 方法返回一个字符串,其中所有空格都被新行替换。在 PowerShell 中,要添加新行,它使用 `r`n

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

在PowerShell中使用replace()将空格替换为换行符

PowerShell String 内置 replace() 方法采用两个参数;要搜索的字符串和要替换为找到的文本的字符串。

 $str = "C# PowerShell NodeJs" 

# Replace all space with a new line
$str.Replace(" ","`r`n")                     

上面的 PowerShell 脚本使用 replace() 方法将字符串中的空格替换为新行

PowerShell replace() 方法需要 2 个参数:

  1. 要在给定字符串中搜索的子字符串
  2. 找到的文本的替换字符串

PowerShell replace() 方法返回一个新字符串,其中字符串中的所有空格都被新行替换。

用新行替换所有空格的上述脚本的输出是:

[玩转系统] 在 PowerShell 中用换行符替换空格

酷提示:如何替换 PowerShell 中第一次出现的字符串!

在 PowerShell 中使用替换运算符将空格替换为换行符

使用 PowerShell replace 运算符,您可以用新行替换字符串中的所有空格。

PowerShell 中的replace 运算符有两个参数:要在字符串中查找的字符串以及找到的文本的替换字符串。

 $str = "C# PowerShell NodeJs" 
      
# Replace all space with new line
 $str -replace ' ', "`r`n"       

上面的 PowerShell 脚本使用替换运算符将字符串中的空格替换为新行。它使用 `r`n 添加新行。

替换运算符有 2 个参数:

  1. 要在字符串中搜索的子字符串
  2. 替换字符串

在第一个示例中,replace 运算符将所有空格替换为新行。

上述用于替换字符串中空格的 Powershell 脚本的输出为:

PS C:\> $str = "C# PowerShell NodeJs"                                                                      

PS C:\> $str -replace ' ', "`r`n"                                                                                       
C#
PowerShell
NodeJs

酷提示:如何使用 PowerShell 替换字符串中的所有单引号!

结论

我希望上面关于如何使用 PowerShell Replace() 方法用字符串中的新行替换所有空格的文章对您有所帮助。

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

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

取消回复欢迎 发表评论:

关灯