powershell取代文本通配符

时间:2016-06-06 13:37:45

标签: regex powershell powershell-v4.0

我有一个csv导出,我得到一些信息。第1行和第2行下面的4行是罚款。

第3行和第4行需要删除“2 x”,并且第4行只需要在逗号(包括逗号)后面省略名称henrietta。

我想使用通配符代替数字

Linda
bobbyjoe
2 x ash
3 x Henrietta,suzyann,waynebruce,parkerpeter

目前即时使用如下。只有,我还没有解决部分问题,我没有在网上找到我理解的答案。

$filepath = "c:\mycsv.csv"

$bad2 = "2 x "
$good2 = `b

$bad2 = "3 x "
$good2 = `b

get-content $filepath  | % { $_ -replace $bad2 , $good2 } | % { $_ -replace $bad3 , $good3 } | set-content $saveloc\tidied-$date.csv

1 个答案:

答案 0 :(得分:4)

您熟悉正则表达式吗?查看的代码Wiki,并查看Reference - What does this regex mean?

PowerShell中的-replace运算符正在使用正则表达式替换,因此它非常容易替换"(任何数字)(空格)(文字x)(空格)":

$bad2 = '\d x '
# or
$bad2 = '[0-9] x '

# better
$bad2 = '^\d x '

get-content $filepath  | % { $_ -replace $bad2, $good2 }

更好的版本将匹配锚定到字符串的开头;这是插入符^的作用。

正则表达式非常强大,PowerShell对它们提供了极好的支持。

相关问题