PowerShell5. Modify ascii text file string with line number string is on. Switch and .NET framework or cmdlets & the pipeline? Which is faster?

后端 未结 2 1277
囚心锁ツ
囚心锁ツ 2021-01-15 02:35

How to modify a string (LINE2 \"line number LINE2 is on\") in a windows ascii text file using search strings that are easy to read and easy to add/modify/delete using PowerS

2条回答
  •  失恋的感觉
    2021-01-15 03:11

    Alternative solution:

    $regex = [Regex]::new('^(.*? (?:AROUND LINE|LINE2) )\d+(.*)$', 'Compiled, IgnoreCase, CultureInvariant')
    $lc = 0
    $updatedLines = & {foreach ($line in [IO.File]::ReadLines($file)) {
        $lc++
        $m = $regex.Match($line)
        if ($m.Success) {
            $g = $m.Groups
            $g[1].Value + $lc + $g[2].Value
        } else { $line }
    }}
    [IO.File]::WriteAllLines($file, $updatedLines, [Text.Encoding]::ASCII)
    

提交回复
热议问题