Powershell remove empty lines from variable

Removing empty lines from a PowerShell variable

In PowerShell, you can remove empty lines from a variable by using regular expressions and the `-replace` operator. The `-replace` operator allows you to replace a specific pattern with another value.

Example:

Let’s say we have a variable named `$text` with the following content:

    $text = @"
    Line 1
    
    Line 2
    Line 3
    
    Line 4
    "@
  

To remove the empty lines from the variable, you can use the following PowerShell command:

    $text -replace '\n+', "`n"
  

The regular expression pattern `’\n+’` matches one or more consecutive newline characters. The replacement value “`n” simply inserts a single newline character, effectively removing the empty lines.

Output:

    Line 1
    Line 2
    Line 3
    Line 4
  

As you can see, the empty lines have been removed from the variable.

Same cateogry post

Leave a comment