【问题标题】:Print missing number from sequence从序列中打印缺失的数字
【发布时间】:2019-03-21 10:22:18
【问题描述】:

我有一个名为 test.txt 的文件,其中有一个序列:

1 3 5 6 7

我想打印丢失的数字,我找到了一个完美的magic code

gc test.txt |% {$i = 1}{while ($i -lt $_){$i;$i++};$i++}

或者这个:

gc test.txt | sort {[int]$_} |% {$i = 1}{while ($i -lt $_){$i;$i++};$i++}

但我想打印 ALL 数字:

  • 绿色列表中的数字
  • RED 列表中缺少的数字

【问题讨论】:

    标签: regex powershell sorting scripting range


    【解决方案1】:

    读取文件,从第一个数字开始,到最后一个数字结束,输出文件中没有的任意数字...

    $TestFile = Get-Content Test.txt|Sort
    [int]$TestFile[0]..[int]$TestFile[-1]|Where{$_ -notin $TestFile}
    

    编辑:糟糕,你想要所有数字。这将需要切换,稍等片刻进行更新。

    $TestFile = Get-Content Test.txt|Sort
    Switch([int]$TestFile[0]..[int]$TestFile[-1]){
        {$_ -notin $TestFile}{Write-Host "$_" -Fore Red;Continue}
       default {Write-Host "$_" -Fore Green}
    }
    

    【讨论】:

    • 酷,它奏效了。顺便说一句,如果我的号码是:0005048 0005049 0005409 0005410 0005411 0005412 0005413 0005414 为什么他们都用 RED 打印?
    • 因为我的脚本将它们评估为数字,所以它评估 5048 5049 5409 5410 5411 5412。如果你知道它们是零填充的,你可以做类似{"$_".Padleft(7,'0') -notin $TestFile}
    【解决方案2】:

    只需在正确的位置插入Write-Host -Fore red/green

    gc test.txt | % {$i = 1}{while ($i -lt $_){write-host -Fore red $i;$i++};write-host -Fore green $i;$i++}
    

    没有别名也一样:

    Get-Content .\test.txt | ForEach-Object {$i = 1}{
       while ($i -lt $_){
         Write-Host -ForegroundColor Red $i
         $i++
       }
       Write-Host -ForegroundColor Green $i
       $i++
     }
    

    【讨论】:

    • 因为在 ForEach-Object 命令中使用开始/处理/结束脚本块是如此非常不寻常 [grin],我想你可能想要使用参数名称,而不仅仅是“按位置”。我不得不多次重新阅读代码,因为我期待 | 进入下一步。 [脸红]
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-15
    相关资源
    最近更新 更多