Say I have a directory with N
log files inside:
file1.log
file2.log
file3.log
...
fileN.log
Which linux
command can I use to print the last n
rows of each of those files above?
I know how to print it for 1 file:
less file1.log | tail -n 5
But I would like to do it simultaneously for all N
files in the directory
CodePudding user response:
A for
loop is not the best, since it will not support all cases. Ex. if you have spaces in your filenames.
To avoid all issues, use:
find . -type f -name "*.log" -exec tail -5 {} \; -print
.
: is the current directory. If your log files are not in the current directory, you can replace the.
by the directory containing the files.-name "*.log"
can be modified to filter your files more precisely. Ex. file*.log.tail -5 {}
will print the last 5 lines. Change the number as you require.- the
-print
option will print the filenames of logs found. But you can omit it if you do not need that information in your display.
CodePudding user response:
Use the command "ls *.log | sort -V | tail -n {number}", where number is the number of output files from the end.
For example, "ls *.log | sort -V | tail -n 5" will output in a directory with ten log files only:
file6.log
file7.log
file8.log
file9.log
file10.log
Without the insert "sort -V" in the middle there will be not a natural sort, but a machine sort, that is, "ls *.log | tail -n 10" will output:
file10.log
file1.log
file2.log
file3.log
file4.log
file5.log
file6.log
file7.log
file8.log
file9.log