GDF*_*uma -1 windows csv powershell left-join
我依靠社区专业知识以最佳方式指导我关注以下主题。
在无法安装 MS-Office 应用程序的 Windows 上运行的专业环境中,我需要向我的团队分发一种方法来加入 2 个 CSV 文件并生成第 3 个 CSV 文件作为输出。就像我们运行 SQL 查询一样:
SELECT f1.*, f1.bar = f2.bar as baz
FROM CSVfile1 as f1
LEFT JOIN CSVfile2 as f2
ON f1.key = f2.key
Run Code Online (Sandbox Code Playgroud)
目前已使用 Excel + VBA 达到目标,但 MS-office 软件包将被删除,并且无法再访问。由于同样的原因,使用 MS-Access 的解决方案是不可想象的。
目标是允许任何机构在没有任何能力和特定安装的情况下实现第三个 CSV 计算机。所以使用 python 或 MS-SQL-Servr 的方法也不好。
我想用 Powshell 脚本来完成,但首先。我不习惯使用PowerShell,但我可以学习。
但在尝试之前,我会问社区这是否是最好的方法?或者如果有更好的解决方案?(要求:Windows 操作系统(最新版本),无 MS-office,无特定安装)。
谢谢你们。
从 v7.2 开始,PowerShell 没有内置连接功能(类似于 SQL 的[1]),尽管Join-Object在GitHub 问题 #14994 中建议添加一个cmdlet ;第三方解决方案的提供,通过PowerShell的画廊(例如JoinModule)。
目前,如果安装第三方工具不是一种选择,您可以使用以下方法推出自己的解决方案,该方法Import-Csv用于加载 CSV 文件、用于查找相应行的辅助哈希表以及Add-Member添加列(属性)。
# Create sample CSV files.
$csv2 = @'
key,bar,quux
key1,bar1,quux1
key2,bar2,quux2
key3,bar3,quux3
'@ > ./CSVFile1.csv
@'
key,bar
key1,bar1
key2,bar2a
'@ > ./CSVFile2.csv
# Import the the 2nd file and load its rows
# (as objects with properties reflecting the columns)
# into a hashtable, keyed by the column 'key' values.
$hash = @{}
foreach ($row in Import-Csv ./CSVFile2.csv) {
$hash[$row.key] = $row
}
# Import the 1st file and process each row (object):
# Look for a matching object from the 2nd file and add
# a calculated column derived from both objects to the
# input object.
Import-Csv ./CSVFile1.csv | ForEach-Object {
$matching = $hash[$_.key]
$_ |
Add-Member -PassThru baz $(if ($matching) { [int] ($matching.bar -eq $_.bar) })
}
Run Code Online (Sandbox Code Playgroud)
通过管道将最后一条语句Export-Csv导出到 CSV 文件。(例如
... | Export-Csv -NoTypeInformation -Encoding utf8 Results.csv)
以上产生以下结果:
key bar quux baz
--- --- ---- ---
key1 bar1 quux1 1
key2 bar2 quux2 0
key3 bar3 quux3
Run Code Online (Sandbox Code Playgroud)
[1] 有一个-joinoperator,但它的目的是将单个数组的元素连接起来形成单个 string。
| 归档时间: |
|
| 查看次数: |
131 次 |
| 最近记录: |