Trevor Mason
Trevor Mason

Reputation: 1

Trying to extract specific lines of text


        {
            "username": "testuser",
            "votecount": "42",
            "votesclaimed": "0",
            "lastvotetime": "2022-11-04 09:08:29",
            "steamid": "000000000000001"
        },

If I have a text file full of these seperated values. I would like to extract just the line that contains the "username": "testuser" and the votecount. It should then output it into a csv with the username and votecount side by side. How could I accomplish this? My outputs have only been so far that all text is output into a single block. Is there any way to achieve this simply? I would like to further add an if statement to the votecount value where as 25>$votecount it would add the letter D by the number taken from votecount. I have that part working but I cannot get it to output how I am wishing.

Ideal output would be:

testuser 42D
testuser2 30D
testuser3 24

Upvotes: 0

Views: 46

Answers (1)

mklement0
mklement0

Reputation: 437197

It looks like your input file is a JSON file, so you should parse it with ConvertFrom-Json, as follows:

Get-Content -Raw file.json |
  ConvertFrom-Json | 
  ForEach-Object { 
    '{0} {1}{2}' -f $_.username, 
                    $_.votecount, 
                    ('', 'D')[[int] $_.votecount -gt 25]
  }

The above produces the desired outputs as shown in your question, with a sample file.json file created as follows:

@'
[
    {
        "username": "testuser",
        "votecount": "42",
        "votesclaimed": "0",
        "lastvotetime": "2022-11-04 09:08:29",
        "steamid": "000000000000001"
    },
    {
        "username": "testuser2",
        "votecount": "30",
        "votesclaimed": "0",
        "lastvotetime": "2022-11-04 09:08:29",
        "steamid": "000000000000001"
    },
    {
        "username": "testuser3",
        "votecount": "24",
        "votesclaimed": "0",
        "lastvotetime": "2022-11-04 09:08:29",
        "steamid": "000000000000001"
    }
]
'@ > file.json

To export to a CSV file, modify the above to output an object with the desired properties, which you can then pass to Export-Csv; e.g.:

Get-Content -Raw file.json |
  ConvertFrom-Json | 
  ForEach-Object { 
    [pscustomobject] @{
       UserName = $_.username
       VoteCount = '{0}{1}' -f $_.votecount, ('', 'D')[[int] $_.votecount -gt 25]
    }
  } |
    Export-Csv -NoTypeInformation -Encoding utf8 out.csv

With the sample JSON, the above creates out.csv with the following content:

"UserName","VoteCount"
"testuser","42D"
"testuser2","30D"
"testuser3","24"

Upvotes: 1

Related Questions