1

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("#") } 
1
  • I used following command ....Get-Content -Path "C:\Test\run.properties" | Where-Object {!$_.StartsWith("#") } ... but this gives both property name and value. But i want only property names Commented Mar 5, 2018 at 17:04

2 Answers 2

2

You can use a regex to remove the values:

Get-Content -Path "C:\Test\run.properties" |
     Where-Object {!$_.StartsWith("#") } | 
     ForEach-Object {
        $_ -replace '=.*'
}
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.