patternshellMinor
Extract version string from text file with Powershell
Viewed 0 times
fileversionwithtextpowershellextractfromstring
Problem
I need to pull the version # out of a Vim script that might look something like:
The expected output is
I'm new to Powershell, so this is what I have so far:
It's just that it feels... kind of verbose. For comparison, here's my *nix version:
Or you could write a similarly concise
Is there any hope for my Windows version being as concise?
" some header blah blah
" Version: 0.1
[a bunch of code]
" Version: fake--use only the first versionThe expected output is
0.1. If a Version # doesn't exist, it should return the empty string or something like that.I'm new to Powershell, so this is what I have so far:
Get-Content somescript.vim -ErrorAction SilentlyContinue |
Select-String '^" Version: (.*)' |
select -First 1 -ExpandProperty Matches |
select -ExpandProperty Groups |
select -Index 1 |
select -ExpandProperty ValueIt's just that it feels... kind of verbose. For comparison, here's my *nix version:
perl -ne '/^" Version: (.*)/ && do { print "$1\n"; exit }' somescript.vim 2>/dev/nullOr you could write a similarly concise
awk scriptIs there any hope for my Windows version being as concise?
Solution
I haven't found a terser approach using only built-ins, but having a little more confidence now in Powershell, I think I'd simply refactor out the group matching code:
Then you could use it like:
In the end, you haven't saved that many lines, but refactoring out the tedious expansions of
filter Select-MatchingGroupValue($groupNum) {
if (! $groupNum) {
$groupNum = 0
}
select -InputObject $_ -ExpandProperty Matches |
select -ExpandProperty Groups |
select -Index $groupNum |
select -ExpandProperty Value
}Then you could use it like:
Get-Content .\somescript.vim -ErrorAction SilentlyContinue |
Select-String '^" Version: (.*)' |
select -First 1 |
Select-MatchingGroupValue 1In the end, you haven't saved that many lines, but refactoring out the tedious expansions of
Matches, Groups, and Value makes the resulting code much clearer IMO.Code Snippets
filter Select-MatchingGroupValue($groupNum) {
if (! $groupNum) {
$groupNum = 0
}
select -InputObject $_ -ExpandProperty Matches |
select -ExpandProperty Groups |
select -Index $groupNum |
select -ExpandProperty Value
}Get-Content .\somescript.vim -ErrorAction SilentlyContinue |
Select-String '^" Version: (.*)' |
select -First 1 |
Select-MatchingGroupValue 1Context
StackExchange Code Review Q#44920, answer score: 3
Revisions (0)
No revisions yet.