【问题标题】:Search for Three Consecutive Lines of Text Inside a File在文件中搜索三个连续的文本行
【发布时间】:2019-07-15 10:04:18
【问题描述】:

问题:我需要在一个文件中搜索一些文本,它包含三行连续行的文本。如何验证(查找是否存在)这些行在文件中?

预期返回值:布尔值


示例输入文件text.txt

one
two
three
four
five

要搜索的示例模式

two
three
four

【问题讨论】:

  • 您应该查看How to Ask 以获取有关提问的提示,以便获得高质量、量身定制的回复。响应者希望MCVE 被关注。对于一些指针,请考虑Select-StringGet-Content
  • 文件中的三行是连续写的吗?行之间是否有换行符和回车符?如果您在文件中找到这些行,您希望代码输出什么?当您找不到这些行时,您希望它输出什么?您需要知道匹配文本的行号吗?区分大小写重要吗?文本文件有多大?这段代码是否预计会遍历许多文本文件?我们可以提供一般性答案,但它们可能不是您所需要的。代码示例会很有帮助。
  • @AdminOfThings 是的,它们与新行/回车是连续的,我只需要知道这些行的存在。
  • 在 Select-String 上使用 -SimpleMatch 参数,或者在 Get-Content 变量上使用 -match 来查找模式,然后 if ($found) {do something} 通知您。跨度>

标签: windows powershell


【解决方案1】:

简单答案

$file = (Get-Content -Raw file.txt) -replace "`r" # removing "`r" if present

$pattern = 'two
three
four' -replace "`r"

$file | Select-String $pattern -Quiet -SimpleMatch

重新编辑。哇。这是一种棘手的方法。在提示符处,$pattern 没有“`r”,但在脚本中却有。这应该作为脚本或在提示符下工作。

$file = (get-content -raw file.txt) -replace "`r"

$pattern = 'two
three
four' -replace "`r"

# just showing what they really are
$file -replace "`r",'\r' -replace "`n",'\n'
$pattern -replace "`r",'\r' -replace "`n",'\n'

# 4 ways to do it
$file -match $pattern
$file | select-string $pattern -quiet -simplematch
$file -like "*$pattern*"
$file.contains($pattern)

# output
one\ntwo\nthree\nfour\nfive\n
two\nthree\nfour
True
True
True
True

嗯,尝试正则表达式。在单行模式下,一个 .可以匹配“`r”或“`n”。

$file = get-content -raw file.txt
$pattern = '(?s)two.{1,2}three.{1,2}four'
# $pattern = 'two\r?\nthree\r?\nfour'
# $pattern = 'two\r\nthree\r\nfour'
# $pattern = 'two\nthree\nfour'
$file -match $pattern
$file | select-string $pattern -quiet

【讨论】:

  • 当我运行它们(所有 6 个测试用例)时,这些都评估为 false。
  • 你是如何制作 $file 和 $pattern 的?它必须和我一样。
  • 我只是将您的脚本复制到一个 ps1 文件中并运行它。
  • 成功了,谢谢。转义的换行符和回车符是有意义的。
猜你喜欢
  • 1970-01-01
  • 2015-12-01
  • 2010-11-02
  • 2015-01-25
  • 1970-01-01
  • 2018-06-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多