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

标签 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的新手,所以不经常使用regex,所以我可能犯了noob错误...
你们有解决方案吗?

最佳答案

内容似乎没有标题,您可以在运行时添加它们。本示例替换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

关于regex - PowerShell正则表达式仅匹配.csv每行中的第一个匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11012593/

相关文章:

windows - 如何从批处理文件运行 PowerShell 脚本

powershell - 无法将参数绑定(bind)到参数 'command',因为它为空。电源外壳

python pandas 读取列名中的 csv 文件错误

python - 从 CSV 加载数据时,QAbstractListModel 不会更新值,但在使用硬编码值时会更新

regex - 如何将数字与 grep 匹配

javascript - 按零件名称获取类(class)数

c++ - 使用正则表达式查找多个字符串的第一个实例

regex - Perl 正则表达式 : howto get open-reading-frames without internal stop-codons?

Powershell - 从数组中的每个字符串中获取变量

php - 使用 currancy 格式的字段将 CSV 导入 MYSQL