拆分一个字符串,然后分配拆分 [英] Split a String and then assign the splits

查看:23
本文介绍了拆分一个字符串,然后分配拆分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本文件,文本文件中有两个名字,就像这样.

I have a text file, in the text file are two names, exactly like this.

汤姆哈迪

布拉德·皮特

我用它来从文件中获取名称并拆分它们.

I use this, to take the names from the file and split them.

$Names = gc C:TempName.txt

ForEach-Object {-Split $Names}

然后如何将每个名字分配给 $FirstName,将每个姓分配给 $LastName?

How do I then assign each first name to $FirstName and each last name to $LastName?

这背后的想法是,更进一步,对于每个 $FirstName,我将为每个名称创建一个特定的单独项目.

The idea behind this is that further down the line, for each $FirstName I will be creating a specific individual item with each name.

我知道在我运行上面的代码后,名称的每个部分都被分配给 $_ 所以我可以对每个部分做同样的事情,即

I understand that after I run the above, each section of the name is assigned to $_ so I can do the same thing with each section i.e

$Names = gc C:TempName.txt

$SplitNames = ForEach-Object {-Split $Names}

ForEach ($_ in $SplitNames) {Write-Host 'Name is' $_}
Name is Tom
Name is Hardy
Name is Brad
Name is Pitt

希望这是有道理的,如果需要更多说明,请告诉我.

Hope this makes sense, please let me know if more clarification is needed.

推荐答案

与@Paxz 相同,但有一些解释和建议:

Same as @Paxz but with some explanation and suggestions:

$Names = @(
    'Brad Pitt',
    'Tom Hardy',
    'Daniel Craig Junior'
)

# the .ForEAch method is used as it's faster then piping data to Foreach-Object
$result = $Names.ForEach({
    # we use the second argument of -Split to indicate 
    # we're only interested in two values
    $tmpSplit = $_ -split ' ', 2

    # we then create an object that allows us to 
    # name things propertly so we can play with it later withoout hassle
    [PSCustomObject]@{
        Input = $_
        FirstName = $tmpSplit[0]
        LastName = $tmpSplit[1]
    }
})

# here we show the result of all our objects created
$result

# enable verbose text to he displayed
$VerbosePreference = 'Continue'

$result.ForEach({
    # here we can easily address the object by its property names
    Write-Verbose "Input '$($_.Input)' FirstName '$($_.FirstName)' LastName '$($_.LastName)'"
})

# disable verbose messages, because we don't need this in production
$VerbosePreference = 'SilentlyContinue'

这篇关于拆分一个字符串,然后分配拆分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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