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

[玩转系统] PowerShell 在换行符上拆分

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

PowerShell 在换行符上拆分


PowerShell字符串Split()函数根据指定的分隔符将字符串拆分为多个子字符串。要在字符串中按换行符进行分割,可以将 Split() 方法与 [Environment::Newline] 结合使用。

如果您的字符串或文本文件具有 CRLF 行分隔符,则可以使用 PowerShell 字符串拆分方法或拆分运算符。

在本文中,我们将讨论如何使用 Split() 方法或拆分运算符为给定字符串或文本文件拆分新行。

PowerShell 按换行符拆分字符串

如果您有一个包含多行字符串的字符串,并且想要在新行上拆分,则可以使用 PowerShell 字符串 split() 方法轻松完成此操作。

$testString = "Welcome to `r`nShellGeek Website"

#Split on new line using Environment::NewLine
$testString.Split([System.Environment]::NewLine,[System.StringSplitOptions]::RemoveEmptyEntries)   

在上面的 PowerShell 脚本中,$testString 包含具有 CRLF(回车和换行)的字符串。

使用 PowerShell 字符串 Split() 方法,我们使用 [Environment]::NewLine 作为分隔符来拆分新行上的字符串。

StringSplitOptions::RemoveEmptyEntries 是一个可选参数,用于从结果中删除任何空条目。

使用 split() 方法后上述 PowerShell 脚本的输出

Welcome to
ShellGeek Website

您还可以使用 split 运算符在 [Environment]::NewLine 或 `r`n 的帮助下在换行符上拆分字符串

$testString = "Welcome to `r`nShellGeek Website" 

# Split the newline using `r`n
$teststring -split "`r`n" 

# Split the newline using Environment::NewLine
$teststring -split [System.Environment]::NewLine  

在上面的 PowerShell 脚本中,我们使用了多种方法使用 Environment::NewLine 或 `r`n 在换行符上分割字符串

在换行符上分割字符串后,上述脚本的输出是:

Welcome to
ShellGeek Website

酷提示:如何在 PowerShell 中将字符串拆分为变量!

PowerShell 按换行符拆分文本文件

您可以使用 PowerShell 中的 Get-Content cmdlet 在换行符上拆分文本文件。 Get-Content 命令默认拆分为新行并返回一个字符串数组。

(Get-Content -Path D:\PS\Alias.txt)   

在上面的 PowerShell 脚本中,Get-Content cmdlet 使用 Path 参数指定文件的名称及其路径。默认情况下,它读取内容并在换行符上拆分它。

将文本文件拆分为新行后,上述 PowerShell 脚本的输出为:

PS C:\> (Get-Content -Path D:\PS\Alias.txt)                                                                             # Alias File
# Exported by : ShellGeek
# Date/Time : 30 July 2022 18:57:47
# Computer : INCORP-EU-117
"foreach","ForEach-Object","","ReadOnly, AllScope"
"%","ForEach-Object","","ReadOnly, AllScope"
"where","Where-Object","","ReadOnly, AllScope"
"?","Where-Object","","ReadOnly, AllScope"
"ac","Add-Content","","ReadOnly, AllScope"
"clc","Clear-Content","","ReadOnly, AllScope"

您还可以使用 PowerShell string Split() 方法使用 [Environment]:: NewLine 在新行上拆分文本文件并返回字符串数组。

# Using the Split method to split the text file on new line
(Get-Content -Path D:\PS\Alias.txt).Split([System.Environment]::NewLine)

# Using the Split operator to split the file on newline
(Get-Content -Path D:\PS\Alias.txt -Raw) -split "`r`n"

结论

我希望上面关于如何在换行符上分割字符串或在换行符上分割文本文件的文章对您有所帮助。

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

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

取消回复欢迎 发表评论:

关灯