简体   繁体   English

Powershell-如何使用点星号将变量传递给选择字符串中的正则表达式

[英]Powershell - How to Pass Variables to a regex in Select-String with Dot Star

Basically i have a text file and i'm trying to grep (select-string) each line for the regex combination 基本上我有一个文本文件,我正在尝试对正则表达式组合的每一行进行grep(选择字符串)

VariableA.*VariableB

This should output any line that looks something like: 这应该输出任何看起来像这样的行:

xxxxxVariableAxxxxxxxxxVariableBxxxx

And when i do it like this it works: 当我这样做时,它可以工作:

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

What i want to do is pass variables into the regex. 我想做的是将变量传递到正则表达式中。 So i defined two arrays 所以我定义了两个数组

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

and then do a for loop over the array slotting in the variables. 然后对变量中的数组插槽进行for循环。 But i cant's get it work. 但是我不能让它工作。 I've tried the following: 我尝试过以下方法:

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

or without using the Pattern/Path switches 或不使用模式/路径开关

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

or with single quotes 或带单引号

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

or trying to define it as a regex variable 或尝试将其定义为正则表达式变量

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

or 要么

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

Basically i think it doesn't pass the variables through correctly to the select-string.. but i can't work out what the problem is 基本上我认为它不能正确地将变量传递给选择字符串..但是我无法解决问题所在

To embed complex expressions use a sub-expression inside the string: $(...) 要嵌入复杂表达式,请在字符串内使用子表达式: $(...)

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

A sub-expression can basically be an entire set of things to be executed: 子表达式基本上可以是要执行的全部事情:

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

You can use the format operator as well: 您也可以使用格式运算符:

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

Or pre-create a variable and embed that: 或预先创建一个变量并将其嵌入:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM