string - 在powershell的全名文本字段中使用姓氏填充变量
问题描述
我有一系列全名,
$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
}
同样,我只想查看姓氏。如何为此调整此代码?
解决方案
为什么不获取所有选项
$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
推荐阅读
- laravel - 给定的凭证数组中缺少“电子邮件”键
- excel - 在 Excel VBA 中选择随机名称时排除计数器编号
- django - django 中的静态图像/媒体文件
- swift - Swift 高效地拆分字符串
- javascript - 如何在任何调度操作上运行 redux-saga 中间件?
- java - 由操作员检查通量流
- javascript - 如何在不使用状态 React 的情况下使用 javascript 调用组件
- java - 读取大文件并在 RDBMS 中写入
- python - Python通过beautifulsoup抓取Expedia数据
- netlogo - Netlogo 乌龟跳过特定补丁