i wanted to printout the last entry of the file without passing in any arguments but how can i able to do it? i know how to print out where argument is supplied and doing a grep to match it.

example inside the file i have:
apple:2:1:3
orange:1:2:3
grape:2:3:4

i wanted only to print out(last entry of my file):
grape:2:3:4

Dani AI

Generated

Short summary: wanted the last line of a file with no arguments. pointed out a sed-based approach and mentioned using tail; both are valid. Below are a few alternative methods, practical tips for edge cases, and performance/portability notes to help pick the right tool.

A simple, portable one-liner using awk (available on virtually all Unix-like systems):

awk 'END{print}' filename

To skip trailing blank lines and print the last non-empty line:

awk 'NF{last=$0} END{print last}' filename

If only POSIX shell builtins are available, a read-loop captures the last line reliably (handles lines without a trailing newline too):

last=
while IFS= read -r line; do
  last="$line"
done < filename
printf '%s\n' "$last"

On Linux, reversing the file and taking the first line is also convenient (note: tac is not always present on other Unixes):

tac filename | head -n 1

Performance and portability notes: for very large files, utilities that seek from the end (the usual implementation of tail) are fastest; line-at-a-time filters scan the whole file and can be slower. Also consider empty files (these methods produce no output), files with Windows CRLF (you may need to strip \r), and whether you want to ignore trailing blank lines. For more on behavior and performance characteristics of standard tools, see the POSIX tail spec (POSIX tail specification) and the GNU awk manual (gawk manual).

Recommended Answers

All 6 Replies

sed -n '$p' filename
commented: I'll have to look into this - don't quite understand how it works. Nice! +1

thanks masijade! thanks for ur help!!!

^ Nice and simple, just the way I like it... though I'm more interested in the sed example.

Or
tail -1 file

True. I like to give somewhat obscure answers to things that I belive are probably/possibly homework questions. That way, if they are not a homework question, the OP has something (s)he can use, and if they are, the teacher knows, as soon as (s)he sees it, that the student probably did not come up with it themselves. ;-)

sed will be slower than tail for huge files. Just a tip

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.