【问题标题】:Populate variable with lastname in a fullname text field in powershell在powershell的全名文本字段中使用姓氏填充变量
【发布时间】:2018-11-27 16:29:57
【问题描述】:

我有一个全名数组,

$doctors = @(
    'John Q. Smith',
    'Mary X. Jones',
    'Thomas L. White',
    "Sonia M. O'Toole"
)

我想只从该字段将姓氏传递给变量。或者也许只有firstinitiallastname。这是我目前给我的名字后缀:

try {
    # add firstnames to list
    $firstnames = New-Object System.Collections.ArrayList
    foreach ($doctor in $doctors) {
        $docname = ($doctor -split '\s')
        $docname = $docname[0]+$docname[-1][0]
        $firstnames += $docname
}

同样,我只想查看姓氏。如何为此调整此代码?

【问题讨论】:

  • $lastName = $docName[-1]
  • 谢谢!我会修补一下,看看有什么用。谢谢你的建议。

标签: string powershell text


【解决方案1】:

EBGreen 准点...

$last_name_only = @()
$first_init_last_name = @()

foreach ($doctor in $doctors) {
    $docname = ($doctor -split '\s')
    $last_name_only += $docname[-1]
    $first_init_last_name += "{0}, {1}" -f $doctor[0], $docname[-1]
}

$last_name_only
$first_init_last_name

【讨论】:

    【解决方案2】:

    为什么不获取所有选项

    $Docs = ForEach ($doctor in $doctors) {
        $First,$Middle,$Last = ($doctor -split '\s')
        [PSCustomObject]@{
           Fullname  = $doctor
           Firstname = $First
           Middle    = $Middle
           Lastname  = $Last
           Docname   = $First+$Last[0]
        }
    }
    $Docs | ft -auto
    
    Fullname         Firstname Middle Lastname Docname
    --------         --------- ------ -------- -------
    John Q. Smith    John      Q.     Smith    JohnS
    Mary X. Jones    Mary      X.     Jones    MaryJ
    Thomas L. White  Thomas    L.     White    ThomasW
    Sonia M. O'Toole Sonia     M.     O'Toole  SoniaO
    
    $Docs.DocName -join ', '
    JohnS, MaryJ, ThomasW, SoniaO
    

    编辑或用

    分割名字
    $doctors = @(
        'John Q. Smith',
        'Mary X. Jones',
        'Thomas L. White',
        "Sonia M. O'Toole"
    )| ConvertFrom-Csv -Delimiter ' ' -Header Firstname.MiddleInitial,Lastname
    

    【讨论】:

    • 我会修补一下,看看有什么用。谢谢你的建议。
    【解决方案3】:

    您可以使用-replace 运算符,它接受一个数组值的 LHS:

    $lastNames = $doctors -replace '.* (.*)$', '$1'
    

    替换操作数中的$1 指的是正则表达式操作数中的第一个(也是唯一一个)捕获组((...))捕获的内容,有效地将每个输入字符串替换为最后一个空格分隔的标记。

    有关-replace 运算符如何工作的更多信息,请参阅我的this answer

    一个完整的例子:

    # The input array.
    # Note that there's no need to use @(...) to create an array literal.
    $doctors =
        'John Q. Smith',
        'Mary X. Jones',
        'Thomas L. White',
        "Sonia M. O'Toole"
    
    # Create a parallel array of last names only.
    $lastNames = $doctors -replace '.* (.*)$', '$1'
    
    $lastNames  # output the result
    

    以上产出:

    Smith
    Jones
    White
    O'Toole
    

    【讨论】:

      猜你喜欢
      • 2021-06-27
      • 2019-08-20
      • 1970-01-01
      • 1970-01-01
      • 2016-02-22
      • 1970-01-01
      • 2021-09-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多