How do I get the last non-empty line of a file using tail in Bash?

前端 未结 7 497
慢半拍i
慢半拍i 2020-12-24 12:26

How do I get the last non-empty line using tail under Bash shell?

For example, my_file.txt looks like this:

hello

相关标签:
7条回答
  • 2020-12-24 13:14

    You can use Awk:

    awk '/./{line=$0} END{print line}' my_file.txt
    

    This solution has the advantage of using just one tool.

    0 讨论(0)
  • 2020-12-24 13:14

    Print the last non-empty line that does not contain only tabs and spaces like this:

    tac my_file.txt | grep -m 1 '[^[:blank:]]'
    

    Note that Grep supports POSIX character class [:blank:] even if it is not documented in its manual page until 2020-01-01.

    File may contain other non-visible characters, so maybe using [:space:] may be better in some cases. All space is not covered even by that, see here.

    0 讨论(0)
  • 2020-12-24 13:15

    How about using grep to filter out the blank lines first?

    $ cat rjh
    1
    2
    3
    
    
    $ grep "." rjh | tail -1
    3
    
    0 讨论(0)
  • 2020-12-24 13:16

    Instead of tac you can use tail -r if available.

    tail -r | grep -m 1 '.'
    
    0 讨论(0)
  • 2020-12-24 13:17

    if you want to omit any whitespaces, ie, spaces/tabs at the end of the line, not just empty lines

    awk 'NF{p=$0}END{print p}' file
    
    0 讨论(0)
  • 2020-12-24 13:19

    If tail -r isn't available and you don't have egrep, the following works nicely:

    tac $FILE | grep -m 1 '.'

    As you can see, it's a combination of two of the previous answers.

    0 讨论(0)
提交回复
热议问题