I would like to remove a empty line in using powershell. Here is my Text
Line 1
Line 2
<Empty line>
<Empty line>
Line 3
Line 4
I have tried using -replace ("`n", "") but it does not work. Please help!
I would like to remove a empty line in using powershell. Here is my Text
Line 1
Line 2
<Empty line>
<Empty line>
Line 3
Line 4
I have tried using -replace ("`n", "") but it does not work. Please help!
$text = """
Line 1
Line 2
Line 3
Line 4
"""
$text -replace "(?m)^\s*`r`n",''
# Or
$text -replace "(?m)^\s*`n",''
regex explained:
(?m) set the multiline flag so ^ matches the beginning of each line and not just the begining of the whole string.
^ matches the beginning of a line
\s* matches any number of white spaces (could also be 0 white spaces)
`r`n matches the end of a line.
Why `r`n or just `n (depending on the machine or file):
\`r = CR (Carriage Return) → Used as a new line character in Mac OS before X
\`n = LF (Line Feed) → Used as a new line character in Unix/Mac OS X
\`r\`n = CR + LF → Used as a new line character in Windows
Or simply read the file as string array and use a Where-Object to let pass only the lines that contain at least one non-whitespace character.
$text = Get-Content -Path 'D:\Thefile.log' |
Where-Object { $_ -match '\S' }
Now you can save this string array in $text back to file, join it with [environment]::NewLine to become a single string again, or...