How do I get the last non-empty line using tail
under Bash shell?
For example, my_file.txt
looks like this:
hello
You can use Awk:
awk '/./{line=$0} END{print line}' my_file.txt
This solution has the advantage of using just one tool.
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.
How about using grep
to filter out the blank lines first?
$ cat rjh
1
2
3
$ grep "." rjh | tail -1
3
Instead of tac
you can use tail -r
if available.
tail -r | grep -m 1 '.'
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
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.