2016-03-01 32 views
1

基本上我有我試圖到grep一個文本文件(選擇弦)各行正則表達式組合PowerShell的 - 如何傳遞變量在選擇串用點星正則表達式

VariableA.*VariableB 

看起來像這應該輸出的任何行:

xxxxxVariableAxxxxxxxxxVariableBxxxx 

當我做這樣的工作原理:

select-string "11568.*19521" d:\sourcefiledir\sourcefile.csv | select -exp line | Out-File c:\destfiledir\destfile.csv -Append 

什我想要做的是將變量傳遞給正則表達式。 所以我定義兩個陣列

$ArrayA = @(23423, 45435, 234142, 24532) 
$ArrayB = @(23423, 23423, 23424, 2342429) 

,然後做一個for循環陣列中的變量開槽過來。但我無法得到它的工作。 我已經試過如下:

select-string -Path D:\somelocation\somefile.csv -Pattern "$ArrayA[j].*$ArrayB[j]" | select -exp line | Out-File c:\somepath\somefile.csv 

或不使用模式/路徑開關

select-string "$ArrayA[j].*$ArrayB[j]" D:\somelocation\somefile.csv | select -exp line | Out-File c:\somepath\somefile.csv 

或用單引號

select-string '$ArrayA[j].*$ArrayB[j]' D:\somelocation\somefile.csv | select -exp line | Out-File c:\somepath\somefile.csv 

,或者試圖把它定義爲一個變量的正則表達式

[regex] $regstring = "$ArrayA[j].*$ArrayB[j]" 
select-string $regstring D:\somelocation\somefile.csv | select -exp line | Out-File c:\somepath\somefile.csv 

select-string -Path D:\somelocation\somefile.csv -Pattern $regstring | select -exp line | Out-File c:\somepath\somefile.csv 

基本上我認爲它不會通過正確傳遞變量來選擇串..但我想不通的問題是什麼

回答

0

要嵌入複雜的表達式使用要執行$(...)

$str = "$($ArrayA[j]).*$($ArrayB[j])" 

一個子表達基本上可以整個一套東西一個:子表達的字符串內

$str = "Blah $((Get-Process | Select-Object -ExpandProperty Name) -join '~') bleh" 

您可以使用格式運算符,以及:

$str = "{0}.*{1}" -f $ArrayA[j],$ArrayB[j] 

或預創建一個變量並嵌入的是:

$aAj = $ArrayA[j] 
$aBj = $ArrayB[j] 
$str = "$aAj.*$aBj" 
+0

真棒感謝briantist!工作過一種享受! 如果您有時間...爲什麼數組變量需要額外的括號和$語法作爲 $($ ArrayA [j])。* $($ ArrayB [j])---作品 而不是 $ ArrayA [j]。* $ ArrayB [j] ----不起作用 – g0pher