3

複数の単語を含むファイルがあります。プログラムに引数として渡した文字を含む単語のみを取得したいと思います。

例: test.txt

apple
car
computer
tree

./select.ps1 test.txt oer

結果は次のようになります。

computer

私はこれを書きました:

foreach ( $line in $args[0] ) {
        Get-Content $line | Select-String -Pattern $args[1] | Select-String -Pattern $args[2] | Select-String $args[3]
}

しかし、たとえば 10 個のパラメーターを使用したいが、常にコードを変更したくない場合はどうすればよいでしょうか? どうすればそれを管理できますか?

4

3 に答える 3

3

2 つのループが必要です。1 つは入力ファイルの各行を処理するループで、もう 1 つは現在の行を各フィルター文字と照合するループです。

$file = 'C:\path\to\your.txt'

foreach ($line in (Get-Content $file)) {
  foreach ($char in $args) {
    $line = $line | ? { $_ -like "*$char*" }
  }
  $line
}

一度に 1 文字よりも複雑な式に一致させたい場合は、さらに作業が必要になることに注意してください。

于 2015-05-05T17:14:15.093 に答える
0

楽しみのために、何か違うことを提案します。

$Items = "apple", "car", "computer", "tree"

Function Find-ItemsWithChar ($Items, $Char) {
    ForEach ($Item in $Items) {
        $Char[-1..-10] | % { If ($Item -notmatch $_) { Continue } }
        $Item
    }
} #End Function Find-ItemsWithChar

Find-ItemsWithChar $Items "oer"

ファイルで $Items 変数をロードする必要があります。

$Items = Get-Content $file
于 2015-05-05T21:58:31.843 に答える
-2

これこれを見てみましょう。

私はまた指摘したかった:

Select-String一度に複数のパターンで複数のアイテムを検索できます。一致させたい文字を変数に保存し、それらすべてを 1 行でチェックすることで、これを有利に利用できます。

$match = 'a','b','c','d','e','f'
Select-String -path test.txt -Pattern $match -SimpleMatch

これにより、次のような出力が返されます。

test.txt:1:apple
test.txt:2:car
test.txt:3:computer
test.txt:4:tree

一致した単語だけを取得するには:

Select-String -Path test.txt -Pattern $match -SimpleMatch | Select -ExpandProperty Line

また

(Select-String -Path test.txt -Pattern $match -SimpleMatch).Line
于 2015-05-05T17:00:48.250 に答える