Search code examples
powershellpowershell-2.0powershell-3.0powershell-4.0powershell-remoting

How to delete only first ocurrence of line without "}" in Powershell?


I try to delete carriage return in a file, all lines have a "}" at end, but some lines, have a return carriage and the "}" its down.... Here an example of my code and file, but doesn't work. Thank You Very Much!!

Original File

The line with "INGENIERIA Y SERVICIOS LOS NOGALES SPA" it's the conflict.

Expected Result

Code:

$InputFile='Original.txt'
$OutPutFile='NewFile.txt'
(Get-Content $InputFile) | ForEach-Object -Begin {
$results = @()
} -Process {
$out = $.Split("}").GetUpperBound(0)
[int]$iOut = [int]$out
if($iOut -lt 1){$.Replace("`r`n","")}else{$_}
} | Set-Content $OutPutFile

Thanks!


Solution

  • You may do the following:

    (Get-Content $InputFile -Raw) -replace '(?<!})\r\n' |
        Set-Content $outputfile
    

    Reading a file using Get-Content without the -Raw or -ReadCount parameters, reads each line and outputs it as an array element. A line is output once its delimiter has been found. The default delimiter for Get-Content is the end of line character. -Raw allows newline characters to be preserved and the file is read as a single string.

    (?<!}) is a negative lookbehind matching only when the preceding character is not a }. Then we simply match \r\n for CRLF.