regex - Powershell如何根据正则表达式仅替换特定列的CSV文件中的值
问题描述
我一直在尝试找到解决这个问题的方法,我正在从一个更大的文件创建一个 CSV,选择特定的列,我从这里得到了很大的支持,并且该任务正在完成,但是我的 CSV 文件包含我的值想替换,例如,“用户名”列,我只想保留 1 个用户,这意味着删除“,”之后的所有内容,我得到了一个看起来像
(,.*$)|(not applicable)|(sscope)
这就是我想用空字符串替换的内容,但我无法让它工作,它有时会删除所有内容。
用户名列中的值如下所示
User Name
B2 cell : not applicable
B3 cell : sscope, sscope
B4 cell : sscope
B5 cell : sscope, sscope, hernhng002, coanbvf001, clacbff01, polsbvcw04, taylor38, milthy12, hic6yth31, carruhgy58, grabngh09, starytht37, milytht937
B6 cell : tamyhg4647adm
B7 cell : moreduj4664
问题 2:如何根据公共键(两者中的名称列)添加来自不同 CSV 文件的列,但只有一个文件具有内存列,我想将其添加到第一个文件中。谢谢
. D:\Data\BF_Scripts\Write-Log.ps1
$filePath = "D:\Data\Input\bigFixDataNew.csv"
#$filePath = "D:\Data\Input\BF_Test_Dec2019.csv"
$System = "D:\Data\Output\System.csv"
$desiredColumnsSystem = @{ expression = {$_.'Internal Computer ID'}; label = 'RESOURCEID' },
@{ expression = {$_.'Computer Name'}; label = 'NAME'},
@{ expression = {$_.'DNS Name'}; label = 'DOMAIN'},
@{ expression = {$_.'DNS Name'}; label = 'USER_DOMAIN'},
@{ expression = {$_.'User Name'}; label = 'USER_NAME'}
$Regex = '(,.*$)|(, sscope)|(sscope)'
Try {
Write-Log -Message 'Starting Creation of System CSV...'
Import-Csv $filePath | Select-Object $desiredColumnsSystem | Sort RESOURCEID -Unique |
Export-Csv -Path $System –NoTypeInformation
$content = Get-Content $System
$content | ForEach-Object {$_ -replace $Regex,''} | Set-Content $System
$size = ((Get-Item $system).length/1KB)
$lastTouchedDate = (Get-Item $system).LastWriteTime
Write-Log -Message "Created the System CSV Successfully !! The size of $system is $size KB and the last write time was $lastTouchedDate"
}
catch
{
Write-Log -Message $_.Exception.Message
}
解决方案
这似乎已经做到了,再次感谢大家
Import-Csv $filePath | Select-Object $desiredColumnsSystem | Sort RESOURCEID -Unique | ForEach-Object {
If ($_.USER_NAME -match $Regex) {
$_.USER_NAME = $_.USER_NAME -replace $Regex,''
}
$_
} |
Export-Csv -Path $System –NoTypeInformation
推荐阅读
- python - ModuleNotFoundError:没有名为“factor_analyzer”的模块 - Python Notebook
- python - 严重挣扎于 sdist - 希望能够在导入时跳过文件夹
- python - Sqlalchemy 查询/过滤器以检查 INSERT Python 上的重复项
- c++ - 如何在 C++ 中实现确定性有限自动机类
- python - For循环没有遍历列表中的所有值?
- json - jq:一个 jq 命令来更新 Json 文件中的多个值
- ssis - SSIS派生列表达式 - 删除前导零
- java - 如何在没有显式代码的情况下在 mule esb 3.9 的 inboud-endpoint 上收听消息的到达?
- asp.net - 在 asp.net mvc 的单元测试中,对象引用未设置为对象问题的实例
- c# - 在 UWP 中禁用游戏手柄导航