【问题标题】:Read a file, count delimiters and output line number with mismatched delimiter读取文件,使用不匹配的分隔符计算分隔符和输出行号
【发布时间】:2020-02-13 21:56:35
【问题描述】:

我有一个名为:test_file.txt 的文件。第二行有 4 个管道分隔符,除第 2 行之外的所有其他行有 3 个管道分隔符。 我只想输出第 2 行,因为它比其他行多了一个分隔符。

$colCnt = "C:\test.txt"
[int]$LastSplitCount = $Null
Get-Content $colCnt | ?{$_} | Select -Skip 1 | %{if($LastSplitCount -and !

($_.split("|").Count -eq $LastSplitCount))

{"Process stopped at line number $($_.psobject.Properties.value[5]) for column count mis-match.";break}

elseif(!$LastSplitCount){$LastSplitCount = $_.split("|").Count}}

【问题讨论】:

  • 您能发布到目前为止的代码,并说明您遇到了什么问题,或者哪里没有用吗?
  • @mclayton ,我尝试的代码被添加到问题中。

标签: powershell count delimiter line-numbers


【解决方案1】:

如果你的文本文件看起来像这样:

blah|using|three|delimiters
blah|using|four |delimiter |characters
blah|using|three|delimiters
blah|using|four |delimiter |characters
blah|using two  |delimiters

以下代码应输出多于(或少于)3 个| 分隔符的行:

$line = 0
switch -Regex -File "C:\test.txt" {
    '^(?:[^|]*\|){3}[^|]*$' { $line++ }   # this line is OK, just increase the line counter
    default { "Bad delimiter count in line {0}: '{1}'" -f ++$line, $_ }
}

输出:

Bad delimiter count in line 2: 'blah|using|four |delimiter |characters'
Bad delimiter count in line 4: 'blah|using|four |delimiter |characters'
Bad delimiter count in line 5: 'blah|using two  |delimiters'

正则表达式详细信息:

^ 在字符串的开头断言位置 (?: 匹配下面的正则表达式 [^|] 匹配任何不是“|”的字符 * 在零次和无限次之间,尽可能多次,按需回馈(贪婪) \|匹配字符“|”字面上地 ){3} 正好 3 次 [^|] 匹配任何不是“|”的字符 * 在零次和无限次之间,尽可能多次,按需回馈(贪婪) $ 断言字符串末尾的位置(或字符串末尾的换行符之前,如果有的话)

【讨论】:

    猜你喜欢
    • 2019-12-07
    • 1970-01-01
    • 1970-01-01
    • 2020-11-21
    • 1970-01-01
    • 2012-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多