gpt4 book ai didi

powershell - -f 空白空间的未知原因

转载 作者:行者123 更新时间:2023-12-02 07:17:44 25 4
gpt4 key购买 nike

基本上我有一个包含姓名和姓氏的文件,例如

Sam, Anderson

我只想更改显示名称的顺序:

Anderson, Sam

这是我的代码:

$variable = Read-Host "would you like the names to be sorted in another way?" 'y,n'
if ($variable -eq 'y') {
$Choice = Read-Host "would you like the names to be sorted based on last or first name?" 'l,f'

if ($Choice -eq 'l') {
$ergebnis | %{"{1}, {0}" -f $_.Split(',')}
}

if ($Choice -eq 'f') {
$ergebnis | %{"{0}, {1}" -f $_.Split(',')}
}
}

当我运行这个 $ergebnis | %{"{0}, {1}"-f $_.Split(',')} 我明白了

Sam, Anderson

然后我改变位置 $ergebnis | %{"{1}, {0}"-f $_.Split(',')}得到这个:

 Anderson, Sam

谁能帮我弄清楚为什么从位置 1 开始输出时出现空白?

$ergebnis 是包含名称的变量。

最佳答案

正如其他人指出的那样,您在逗号处拆分字符串,并且仅在逗号处拆分,从而保留姓氏之前的前导空格。这意味着运行 "{0}, {1}"-f $_.Split(',') 应该给你一个结果

Sam,  Anderson

with 2 spaces after the comma, whereas "{1}, {0}" -f $_.Split(',') should give you a result of

 Anderson, Sam

with one space after the comma and another before the surname.

You can trim leading/trailing whitspace after splitting the string, as has been suggested already, but that requires PowerShell v3 or newer, as it makes use of member enumeration to call Trim() on all results of the Split() operation.

An alternative is to use the -split operator with a regular expression that includes whitespace in the pattern by which the string is split. That way whitespace before or after the comma is automatically removed. For good measure you could Trim() the input string to remove spurious whitespace at the beginning or end of the string before splitting it.

$ergebnis | ForEach-Object { "{0}, {1}" -f ($_.Trim() -split '\s*,\s*') }

关于powershell - -f 空白空间的未知原因,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56457679/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com