PowerShell正则表达式仅匹配.csv中每行中的第一个匹配项

时间:2012-06-13 10:04:54

标签: regex powershell csv

我们说我有一个看起来有点像这样的.csv文件:

"first_foo","first_foo"
"first_bar","first_bar"
"second_foo","second_foo"
"second_bar","second_bar"

使用PS脚本我想让它看起来像这样:

"first","first_foo"
"first","first_bar"
"second","second_foo"
"second","second_bar"

我在考虑使用这样的东西:

$regex=[regex]"first*";
$regex.Replace('"first_foo","first_foo"',"first",1)

但它不起作用。我是PowerShell的新手并且经常不使用正则表达式,所以我可能会犯下noob错误...... 你们有解决方案吗?

1 个答案:

答案 0 :(得分:1)

看起来内容没有标题,您可以在运行时添加它们。此示例替换col1值并从字符串末尾删除“_foo”或“_bar”:

Import-Csv test.csv -Header col1,col2 | Foreach-Object {
    $_.col1 = $_.col1 -replace '(_foo|_bar)$'
        $_
}

col1   col2      
----   ----      
first  first_foo 
first  first_bar 
second second_foo
second second_bar