我是 Powershell 的新手,但我已經盡力了。有一個 .csv 檔案,小例子:
id,location_id,name,title,email,directorate
1,1, Amy lee,Singer,,
2,2,brad Pitt,Actor,,Production
3,5,Steven Spielberg,Producer,[email protected],Production
需要:
- 將名字和姓氏更改為大寫,例如 Brad Pitt, Amy Lee。
- 使用名字 姓氏的首字母模式創建電子郵件,全部小寫,@google.com 和 location_id 中的值,例如 - [email protected]、[email protected]
- 將其保存到新的 file.csv,具有相同的結構,例如:
id,location_id,name,title,email,directorate
1,1, Amy Lee,Singer,[email protected],
2,2,Brad Pitt,Actor,[email protected],Production
3,5,Steven Spielberg,Producer,[email protected],Production
我寫了一個腳本,它的命令一個一個地執行任務,但不知道如何保存它沒有新的 .csv 檔案:
param (
[string] $file_path
)
$inputFile = Import-Csv -Path $file_path
foreach ($line in $inputFile) {
$line.name = (Get-Culture).TextInfo.ToTitleCase($line.name)
$firstName = $line.name.split(" ")[0]
$lastName = $line.name.split(" ")[1]
$newEmail = ($firstName[0] $lastName $line.location_id "@google.com").toLower()
}
也許,有更干凈的解決方案?
uj5u.com熱心網友回復:
您的代碼已接近完成,但這是一種更簡單的方法。您已經在使用TextInfo.ToTitleCase,但對于電子郵件地址,您可以使用-replace運算子和一些正則運算式來簡化它。
您可以在此鏈接中找到有關正則運算式模式的資訊:https ://regex101.com/r/WKF9R5/1
$txtInfo = [cultureinfo]::InvariantCulture.TextInfo
$csv = Import-Csv path\to\csv.csv
foreach($line in $csv) {
$name = $line.name
$line.name = $txtInfo.ToTitleCase($name)
# Example: 'brad Pitt' => bPitt
$line.email = ($name -replace '(?<=^\w{1})\w \s').ToLower() $line.location_id '@google.com'
}
$csv | Export-Csv path\to\newcsv.csv -NoTypeInformation
在問題中使用 Csv 的最終輸出:
id location_id name title email directorate
-- ----------- ---- ----- ----- -----------
1 1 Amy Lee Singer [email protected]
2 2 Brad Pitt Actor [email protected] Production
3 5 Steven Spielberg Producer [email protected] Production
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/528434.html
標籤:电源外壳
