jks
jks

Reputation: 129

Displaying only property name from property file using PowerShell

I have a vendor properties file and it has property name and values. Now I have to read property file and display only property names.

Below are some property names and its values.

ipaddr=10.1.1.1,12.4.5.6
ports=2345
location=anywhere

I want my output to display like below

ipaddr
ports
location

I used the following command to read the file:

Get-Content -Path "C:\Test\run.properties" | 
    Where-Object {!$_.StartsWith("#") } 

Upvotes: 1

Views: 587

Answers (2)

mklement0
mklement0

Reputation: 440297

To complement Martin Brandl's helpful answer:

For small files such as properties files, you can both simplify and speed up processing by reading all lines up front and then using PowerShell's operators, many of which can operate on array-valued LHS values:

@(Get-Content "C:\Test\run.properties") -notmatch '^#' -replace '=.*'
  • @(Get-Content "C:\Test\run.properties") reads all lines of the input file into an array

    • @(...), the array sub-expression operator, ensures that the result is indeed an array; otherwise, if the file happened to contain only a single line, you'd get a string back, which would change the behavior of -notmatch.
  • -notmatch '^#' only outputs those array elements (lines) that do not start (^) with a # char.

  • -replace '=.*' the operates on the remaining lines, effectively removing the part of the line that starts with =. (.* matches any sequence of characters through the end of the line, and by not specifying a replacement string, the matching part is effectively removed).

The fastest alternative is presumably the use of switch -file -regex:

switch -file -regex "C:\Test\run.properties" { '^#' {continue} default {$_ -replace '=.*'} }
  • -file tells switch to process the lines of the specified files one by one.

  • -regex tells it to interpret the branch conditionals ('^#', in this case) as regular expresions.

  • Branch conditional '^#' again matches lines that start with #, and continue proceeds to the next input line, effectively ignoring them.

  • Branch conditional default applies to all remaining lines, and, as above, $_ -replace '=.*' removes everything starting with the = char. Automatic variable $_ represents the input line at hand.

Upvotes: 0

Martin Brandl
Martin Brandl

Reputation: 59011

You can use a regex to remove the values:

Get-Content -Path "C:\Test\run.properties" |
     Where-Object {!$_.StartsWith("#") } | 
     ForEach-Object {
        $_ -replace '=.*'
}

Upvotes: 2

Related Questions