如何替换命名捕获的值

如何替换命名捕获的值

源txt文件:

,,leia,Arrears,TESTaffil,,User,,,,,,286619,,,
,,anakin,Arrears,TESTstud,,User,,,,,,304119,,,
,,r2d2,Arrears,TESTstud,,User,,,,,,999333,,,
,,deathstar,Arrears,TESTaffil,,User,,,,,,999111,,,

输出

,,leia,Arrears,TESTaffil,,User,,,,,,286619,,,
,,anakin,Arrears,TESTstud,,User,250,,,,,304119,,,
,,r2d2,Arrears,TESTstud,,User,250,,,,,999333,,,
,,deathstar,Arrears,TESTaffil,,User,,,,,,999111,,,

我尝试使用 csv get-content 但文本没有标题,select-string 怎么样?

答案1

您的文件似乎有 16 个字段,但没有标题。如果您提供这些标题,您仍然可以对此使用 Import-Csv。然后,使用列名,您可以单独指定所有字段。

就像是

# create an array of headers, In this example, I'm just using 'Col_1' .. 'Col_16'
# It would of course be better to name the fields for what they contain, but only you would know that..
$headers = 1..16 | ForEach-Object { "Col_$_" }

# Now import the file so we get an array of **objects**. Each object will have 16 properties.

$data = Import-Csv -Path 'X:\SomeFolder\TheFile.csv' -Header $headers
# loop through the rows of the data and update when needed
foreach ($item in $data) {
    # only change data if the field at 'Col_5' contains 'TESTstud'
    if ($item.Col_5 -eq 'TESTstud') {
        # update the field next to Col_7 (the field containing 'User')
        $item.Col_8 = 'SomeReplacementValue'
    }
}

# Save this updated data as (new) proper CSV file
$data | Export-Csv -Path 'X:\SomeFolder\TheUpdatedFile.csv' -NoTypeInformation

相关内容