How replace text and endline in multiple file in powershell?

Viewed 70

i have multiple files like this

TEST:200333
75252
TEST:198234
201756
TEST:201616
274
TEST:200118
934521
TEST:123456
1234

and I want an output like this

200333;75252
198234;201756
201616;274
200118;934521
123456;1234

I tried this code but it doesn't work: powershell -Command "(gc myFile.txt) -replace 'TEST:(\.+)\r\n(\.+)\r', '\1;\2' | Out-File -encoding ASCII mynewFile.txt"

2 Answers

You can use

powershell -Command "(gc myFile.txt -Raw) -replace '(?m)^TEST:(\d+)\r?\n(\d+)\r?$', '$1;$2' | Out-File -encoding ASCII mynewFile.txt"

Or,

powershell -Command "[system.io.file]::ReadAllText('myFile.txt')  -replace '(?m)^TEST:(\d+)\r?\n(\d+)\r?$', '$1;$2' | Out-File -encoding ASCII mynewFile.txt"

See the regex demo. Note the use of -Raw option that slurps the whole file into a single string.

enter image description here

The regex matches

  • (?m) - multiline mode on
  • ^ - line start
  • TEST: - some fixed text
  • (\d+) - Group 1: one or more digits
  • \r?\n - a CRLF (carriage return + line feed)/LF (line feed) line ending
  • (\d+) - Group 2: one or more digits
  • \r? - an optional CR (carriage return)
  • $ - end of a line.

A no-regex approach that just concatenates every other line:

powershell -Command "gc myFile.txt | % {$i=0}{if($i++%2){"$prev;$_"}else{$prev=$_.Substring(5)}} | sc mynewFile.txt -enc ASCII"

Less code-golfy version:

Get-Content myFile.txt | ForEach-Object -Begin {$i = 0} {
    if ($i++ % 2 -ne 0) {         # odd line
        "$prev;$_"                #   output "value from previous line;current line"
    } else {                      # even line
        $prev = $_.Substring(5)   #   remember value, cut off the "TEST:"
    }
} | Set-Content mynewFile.txt -Encoding ASCII
Related