How to tail/grep/awk the last N bytes of a file, rather than lines

cattail

I have an application that is logging to a plain text log file (myapp.log) but it doesn't seem to be writing new line characters at the end of each log entry. If I execute a command like tail -n 50 myapp.log I actually receive hundreds of "lines" of text (log entries).

This log file is very large, roughly 1GB, who knows how long ago the last CR and/or LF was inserterd. How can I just grab say, the last 2MBs for example?

Best Answer

Using the -c switch (2MB = 2 * 1024 * 1024 = 2097152 bytes):

tail -c 2097152 myapp.log

Thanks to Petr Uzel for the suggestion. Some tail implementations allow to add a unit to print the last kilobytes (k) or megabytes (m), like:

tail -c 2m myapp.log

However please note that it is not standard (in none of POSIX, UNIX (SUS) or Linux (LSB)) and not portable. Also note that since the terms "Mega"/"kilo"... and their abbreviations (M, k...) have ambiguous meanings (1000 vs 1024), there's not much guarantee of what this or that implementation of tail will mean by 2m (though the current versions of the current implementations that do support it seem to be going for the 1024 variant).

Related Question