在 PowerShell 中仅打印非空行

mad*_*key 2 regex powershell parsing

我有一个包含多行的文本文件。许多都是空白的,至少我是通过查看文件内容来假设的。我只想编写/打印包含文本的行。我遇到麻烦了。这是我的代码:

$test = Get-Content -Path '.\dummy-file.html'

# convert html file to text, save only the relevant info (no tags)
foreach ($line in $test) {
    $newline = $line -split ("<.*?>") -split ("{.*?}") # remove html and css tags
    $newline -replace "`n","" # thought this would get rid of blank lines. it doesn't
    $newline >> "test-ouput.txt" # save to new file
}

# read text file, print only lines with text
$test.ForEach({$_ -notmatch "`n"})

Run Code Online (Sandbox Code Playgroud)

上面的代码不起作用,仅将布尔值打印到控制台,即使这样,它们的值也是错误的。考虑到 $test 的前 10 行,正确的输出应该只有两行文本,其中八行是空白。但是,会打印空白行。

我是正则表达式的新手,假设它与此有关。我对PowerShell的理解也是新手。谢谢。

San*_*zon 5

不使用正则表达式的一个简单解决方案是使用String.IsNullOrWhiteSpace(String)Method

Get-Content -Path '.\dummy-file.html' | Where-Object {
    -not [string]::IsNullOrWhiteSpace($_)
}
Run Code Online (Sandbox Code Playgroud)

它可以读作,该不是空字符串空格的所有

如果您想使用正则表达式进行测试,可以使用-match运算符\S正则表达式中匹配任何非空白字符。

Get-Content -Path '.\dummy-file.html' | Where-Object {
    $_ -match '\S'
}
Run Code Online (Sandbox Code Playgroud)

下面是一个例子:

PS /> @'
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed
         
a, luctus sit amet augue. Aliquam finibus,
          
felis luctus tincidunt dapibus, justo tellus finibus risus, et
          
in pharetra risus. Lorem ipsum dolor
'@ -split '\r?\n' | Where-Object { -not [string]::IsNullOrWhiteSpace($_) }

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed
a, luctus sit amet augue. Aliquam finibus,
felis luctus tincidunt dapibus, justo tellus finibus risus, et
in pharetra risus. Lorem ipsum dolor
Run Code Online (Sandbox Code Playgroud)