将文件中的关键字(模式)与多个文件进行匹配

Match keywords (patterns) from file against multiple files

抱歉标题晦涩难懂,这是我的问题和我想做的事情。

我的文件:

\mydir\keywords.txt
\mydir\textfile1.txt
\mydir\textfile2.txt
\mydir\textfile3.txt
etc

我 "keywords.txt" 有很多关键字(字符串),我想将它们与 "textfile1.txt" 等进行匹配,并收到包含匹配项的文件名的答案。

$keywords = Get-Content -Path '\mydir\keywords.txt' | Out-String
Select-String -Path '\mydir\*.txt' -Pattern $keywords

即递归搜索 \mydir\ 中的所有 .txt 文件,并使用文件 "keywords.txt" 的内容作为关键字进行搜索。

Get-Content 默认情况下 returns 值作为数组,Out-String 应将其转换为字符串。

感谢大家的帮助!

从您的代码中删除 | Out-String 部分,我相信它会按您的预期工作。这是因为 Get-Content 将在 $Keywords 中创建一个字符串数组,而 -Pattern 参数接受字符串数组输入:

您还应该使用 -SimpleMatch,除非您希望您的关键字被解释为 RegEx 模式。

Select-String -Path '\mydir\*.txt' -Pattern (Get-Content -Path '\mydir\keywords.txt') -SimpleMatch