如何在PowerShell中添加统计特殊字符的新列
PowerShell 新增符号统计列的方法
先看你的原始数据:
| Example Col | Example Col2 |
|---|---|
| Cell 1 | words : words2 = |
| Cell 3 | examplewords:continued |
你需要新增第三列,统计第二列里:和=的总数量,用PowerShell的计算属性就能实现,新手也能快速上手:
直接可用的代码
# 先模拟你的数据(如果是从CSV读取,替换成Import-Csv命令即可) $originalData = @( [PSCustomObject]@{ 'Example Col' = 'Cell 1' 'Example Col2' = 'words : words2 =' }, [PSCustomObject]@{ 'Example Col' = 'Cell 3' 'Example Col2' = 'examplewords:continued' } ) # 新增统计列并输出结果 $originalData | Select-Object *, @{ Name = '符号统计数' # 可自定义列名 Expression = { # 匹配所有:和=,统计出现次数 ($_.['Example Col2'] | Select-String '[:=]' -AllMatches).Matches.Count } }
代码说明
Select-Object *:保留原有所有列,避免数据丢失@{Name='符号统计数'; Expression={...}}:定义计算属性,Name是新列名称,Expression内写统计逻辑Select-String '[:=]' -AllMatches:在第二列文本中匹配所有:和=符号.Matches.Count:获取匹配到的符号总数量,即你需要的统计结果
运行后会得到如下结果:
| Example Col | Example Col2 | 符号统计数 |
|---|---|---|
| Cell 1 | words : words2 = | 2 |
| Cell 3 | examplewords:continued | 1 |
如果你的数据来自CSV文件,只需将模拟数据部分替换为:
$originalData = Import-Csv -Path '你的CSV文件路径.csv'
再执行后续代码即可。
内容的提问来源于stack exchange,提问作者Jasmine
相关产品推荐
相关产品推荐

