55

ファイル内のパターンを見つけようとしています。Select-String行全体ではなく、一致した部分だけを使用して一致する場合。

これを行うために使用できるパラメーターはありますか?

例えば:

私がやったら

select-string .-.-.

ファイルには次の行が含まれていました:

abc 1-2-3 abc

行全体が返されるのではなく、1-2-3だけの結果を取得したいと思います。

Powershellに相当するものを知りたいgrep -o

4

8 に答える 8

41

あるいは単に:

Select-String .-.-. .\test.txt -All | Select Matches
于 2009-05-01T18:06:59.423 に答える
31

デビッドは正しい道を進んでいます。[regex] は System.Text.RegularExpressions.Regex の型アクセラレータです。

[regex]$regex = '.-.-.'
$regex.Matches('abc 1-2-3 abc') | foreach-object {$_.Value}
$regex.Matches('abc 1-2-3 abc 4-5-6') | foreach-object {$_.Value}

冗長すぎる場合は、関数でラップできます。

于 2009-04-30T00:25:46.270 に答える
28

私は他のアプローチを試しました: Select-String は、使用できるプロパティ Matches を返します。すべての一致を取得するには、-AllMatches を指定する必要があります。それ以外の場合は、最初のもののみを返します。

私のテストファイルの内容:

test test1 alk atest2 asdflkj alj test3 test
test test3 test4
test2

スクリプト:

select-string -Path c:\temp\select-string1.txt -Pattern 'test\d' -AllMatches | % { $_.Matches } | % { $_.Value }

戻り値

test1 #from line 1
test2 #from line 1
test3 #from line 1
test3 #from line 2
test4 #from line 2
test2 #from line 3

select-String (technet.microsoft.com)

于 2009-04-30T06:52:02.113 に答える
14

男に釣りを教えるという精神で...

やりたいことは、select-string コマンドの出力をGet-memberにパイプすることです。これにより、オブジェクトが持つプロパティを確認できます。それを行うと、「Matches」が表示され、出力を にパイプすることでそれを選択できます| **Select-Object** Matches

私の提案は、次のようなものを使用することです:select linenumber、filename、matches

例: stej のサンプル:

sls .\test.txt -patt 'test\d' -All |select lineNumber,fileName,matches |ft -auto

LineNumber Filename Matches
---------- -------- -------
         1 test.txt {test1, test2, test3}
         2 test.txt {test3, test4}
         3 test.txt {test2}
于 2009-04-30T15:19:28.943 に答える