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

[玩转系统] PowerShell 将换行符替换为逗号

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

PowerShell 将换行符替换为逗号


在 PowerShell 中,`n 用于添加新行。要在 PowerShell 中用逗号替换新行,请使用 `r`n 检查它是否包含新行,并使用 PowerShell Replace() 方法用逗号替换新行。

在本文中,我们将讨论如何使用 PowerShell Replace() 方法将字符串中的新行替换为逗号,并使用 PowerShell replace 运算符替换新行在 PowerShell 字符串中使用逗号。

PowerShell 使用replace() 方法用逗号替换换行符

使用 PowerShell Replace() 方法将新行替换为逗号。 replace() 有两个参数;要查找的字符串和要替换为 PowerShell 字符串中找到的文本的字符串。

假设您有一个包含多行字符串的字符串。使用`r`n字符(CRLF)检查字符串是否包含回车符和换行符,如果字符串包含换行符则返回true。

要使用 PowerShell Replace() 方法将换行符替换为逗号,请参阅以下代码。

$str = "Hello SysAdmin, Welcome to PowerShell Programming.
Let's begin your Active Directory management using the PowerShell journey here.
Refer the link https://shellgeek.com/tag/active-directory-2/"

# Check if the string contains carriage return
$str.Contains("`r")   
True

# Check if the string contains new line
$str.Contains("`n")

# Replace newline with comma
$str.Replace("`r`n",",")
 

在上面的 PowerShell 脚本中,$str 变量存储一个多行字符串。我们使用 `r`n 来检查字符串是否包含回车符和换行符。

通过 $str 调用 Replace() 方法,将新行替换为给定 PowerShell 字符串中的逗号。

它使用 `r`n 作为第一个参数来搜索字符串中的新行,并使用逗号作为第二个参数来替换找到的文本。

使用 replace() 方法将换行符替换为逗号的上述 PowerShell 脚本的输出是:

[玩转系统] PowerShell 将换行符替换为逗号

酷提示:如何在 PowerShell 中用通配符替换!

使用 PowerShell 替换运算符将换行符替换为逗号

使用PowerShell替换运算符,它可以用逗号替换新行。

让我们考虑上面的变量 $str,它包含一个多行字符串。

 $str = "Hello SysAdmin, Welcome to PowerShell Programming.
Let's begin your Active Directory management using the PowerShell journey here.
Refer the link https://shellgeek.com/tag/active-directory-2/"  

# Replace newline with comma using replace operator
$str -replace '\r\n',','

在上面的 PowerShell 脚本中,我们在 $str 变量上使用 PowerShell replace 运算符,以使用 \r\n 检查回车符和换行符> 并替换为逗号

使用 PowerShell 替换运算符,您需要使用 \r\n 来检查 CRLF

上述用逗号替换新行的 PowerShell 脚本的输出是:

PS C:\> $str
Hello SysAdmin, Welcome to PowerShell Programming.
Let's begin your Active Directory management using the PowerShell journey here.
Refer the link https://shellgeek.com/tag/active-directory-2/

PS C:\> $str -replace '\r\n',','
Hello SysAdmin, Welcome to PowerShell Programming.,Let's begin your Active Directory management using the PowerShell journey 
here.,Refer the link https://shellgeek.com/tag/active-directory-2/

PS C:\> 

结论

希望上述有关如何使用 PowerShell Replace() 方法或 PowerShell Replace 运算符用逗号替换换行符的文章对您有所帮助。

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

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

取消回复欢迎 发表评论:

关灯