在文件内搜索三行连续文本

时间:2019-07-03 21:11:21

标签: windows powershell

问题::我需要在文件内搜索一些文本,该文件包含三行连续行文本。如何验证(确定是否存在)这些行在文件中?

期望的返回值:布尔值


示例输入文件 text.txt

one
two
three
four
five

要搜索的示例模式

two
three
four

1 个答案:

答案 0 :(得分: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

嗯,尝试使用正则表达式。在单行模式下,a。可以匹配“`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