在PowerShell中的新行上拆分带有空格的字符串 [英] Split a string with spaces on a new line in PowerShell

查看:68
本文介绍了在PowerShell中的新行上拆分带有空格的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个 PowerShell 脚本,我在其中输入一个长字符串(来自 CSV 文件),格式如下:

I'm working on a PowerShell script where I take an input of a long string (from a CSV file) in the format:

第一组名称
第二组名称
第三组名称
...

Group One Name
Group Two Name
Group Three Name
...

我正在尝试解析它

($entry.'Group Name').split("`n ") | %{
    if ($_) {
        # Do something with the group name
        $_
    }
}

我想得到如下输出:

第一组名称
第二组名称
第三组名称
...

Group One Name
Group Two Name
Group Three Name
...

但结果是:



姓名

两个
...

Group
One
Name
Group
Two
...

推荐答案

String.Split() 是要拆分的字符列表,而不是要匹配然后拆分的字符序列.您现有的代码将在换行符处拆分,并将在空格处拆分.

The string argument in String.Split() is a list of characters to split on, not a sequence of characters to match and then split on. Your existing code will split on newline, and will split on space.

如果您只想在换行符上拆分,请使用:

If you only want to split on newline, use:

.split("`n")

如果要在换行符后跟空格的字符序列上进行拆分,可以使用 Regex.Split():

If you want to split on the character sequence of a newline followed immediately by a space, you can use Regex.Split():

[Regex]::Split($entry.'Group Name',"`n ") | ...

或者,您可以使用 -split 运算符,它也可以按字符串而不是字符列表进行拆分:

Alternately, you can use the -split operator, which also splits by a string and not a list of characters:

$entry.'Group Name' -split "`n "

这篇关于在PowerShell中的新行上拆分带有空格的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆