【问题标题】:Match keywords (patterns) from file against multiple files将文件中的关键字(模式)与多个文件匹配
【发布时间】:2017-08-09 13:07:42
【问题描述】:

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

我的文件:

\\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 默认将值作为数组返回,Out-String 应该将它们转换为字符串。

感谢所有帮助!

【问题讨论】:

  • 我认为您希望它们作为一个数组,因为-Pattern 接受数组输入。删除 Out-String 部分。

标签: regex powershell select-string


【解决方案1】:

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

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

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

【讨论】:

  • 感谢您的帮助,您的回答和@MarkWragg 都给了我我想要的东西,我实际上忽略了这一点,因为这两个答案也会转储整个数组,因为它使用“keywords.txt”找到匹配项,而且搜索所有 txt 文件 (*.txt)。我删除了keywords.txt并将其放在另一个文件夹中并且它起作用了:D所以我的实际代码是:$content = Get-Content '\\mydir1\keywords.txt' Select-String -Path '\\mydir2\*.txt' -pattern $content
猜你喜欢
  • 1970-01-01
  • 2022-01-07
  • 2022-11-07
  • 2011-06-03
  • 2020-12-08
  • 2014-11-10
  • 2017-12-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多