【问题标题】:How to read the second-to-last line in a file using Bash?如何使用 Bash 读取文件中的倒数第二行?
【发布时间】:2011-08-11 07:35:44
【问题描述】:

我有一个文件,最后三行如下。我想检索倒数第二行,即100.000;8438; 06:46:12

.
.
.
99.900; 8423;   06:44:41
100.000;8438;   06:46:12
Number of patterns: 8438

我不知道行号。如何使用 shell 脚本检索它?提前感谢您的帮助。

【问题讨论】:

    标签: linux bash shell


    【解决方案1】:

    https://stackoverflow.com/a/7671772/5287901 启发的短 sed one-liner

    sed -n 'x;$p'
    

    解释:

    • -n安静模式:不自动打印模式空间
    • x:交换模式空间和保持空间(保持空间现在存储当前行,模式空间存储上一行,如果有)
    • $:在最后一行,p:打印模式空间(上一行,在本例中为倒数第二行)。

    【讨论】:

      【解决方案2】:

      试试这个:

      tail -2 yourfile | head -1
      

      【讨论】:

      • 看到这个明显的答案,我不得不去寻找它……
      【解决方案3】:

      使用这个

      tail -2 <filename> | head -1
      

      【讨论】:

        【解决方案4】:

        edsed 也可以。

        str='
        99.900; 8423; 06:44:41
        100.000;8438; 06:46:12
        Number of patterns: 8438
        '
        
        printf '%s' "$str" | sed -n -e '${x;1!p;};h'                     # print last line but one
        printf '%s\n' H '$-1p' q | ed -s <(printf '%s' "$str")           # same
        printf '%s\n' H '$-2,$-1p' q | ed -s <(printf '%s' "$str")       # print last line but two
        

        【讨论】:

          【解决方案5】:

          发件人:Useful sed one-liners 埃里克·佩门特

          # print the next-to-the-last line of a file
          sed -e '$!{h;d;}' -e x              # for 1-line files, print blank line
          sed -e '1{$q;}' -e '$!{h;d;}' -e x  # for 1-line files, print the line
          sed -e '1{$d;}' -e '$!{h;d;}' -e x  # for 1-line files, print nothing
          

          您不需要所有这些,只需选择一个即可。

          【讨论】:

            【解决方案6】:

            澄清已经说过的话:

            ec2thisandthat | sort -k 5 | grep 2012- | awk '{print $2}' | tail -2 | head -1
            
            snap-e8317883
            snap-9c7227f7
            snap-5402553f
            snap-3e7b2c55
            snap-246b3c4f
            snap-546a3d3f
            snap-2ad48241
            snap-d00150bb
            

            返回

            snap-2ad48241
            

            【讨论】:

              【解决方案7】:
              tac <file> | sed -n '2p'
              

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 2014-09-20
                • 1970-01-01
                • 2022-01-23
                • 2023-01-17
                • 2014-02-26
                • 2010-09-14
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多