Reputation: 135
I have several logfiles differing by time stamp. I want to echo the filename with time stamp and the last few lines (see example).
How can I refer to date and time and to just the filename?
#!/bin/bash
for file in $(ls -l /somePath/log.out*)
do
echo -e "Date: $creationDate - Time: $creationTime - File: `basename ${file}`"
echo -e "`tail -n5 $file`"
done
Upvotes: 0
Views: 2957
Reputation: 941
The output of ls -l
is meant to be human readable, rather than suitable for scripts.
Example from my machine:
$ ls -l /
total 22
-rw-r--r--. 1 root root 0 Nov 7 17:41 1
lrwxrwxrwx. 1 root root 7 Feb 4 2016 bin -> usr/bin
dr-xr-xr-x. 6 root root 1024 Dec 27 11:20 boot
# ...
As you can see, the items modified last year get the year instead of time. Of course you can add more options to get around that, like with --time-style=+%Y-%m-%d %H:%M:%S %4Z"
you can get 2017-03-16 17:31:12 EET
. Once you throw enough options to make the output somewhat reliable, you can start parsing it, which depending on the files can also prove more complex.
That said, unless you are stuck with ls
and for
loops for some reason, it would be better to use find
, which does a great job in finding and displaying files and directories and their details, as well as running commands on them.
find /somePath/log.out* -printf "Date: %TY-%Tm-%Td - Time: %TT - File: %f\n" -exec tail -n5 {} \;
or perhaps better
find /somePath/ -maxdepth 1 -name "log.out*" -type f -printf "Date: %TY-%Tm-%Td - Time: %TT - File: %f\n" -exec tail -n5 {} \;
Check man find
for more details on its options and how to further format the output (eg. date and time formats).
One more note: In Linux usually there is no such thing as create date/time. The files store the times for their last modification, change and maybe access (if enabled for the file system). The above command uses the modification time.
Upvotes: 1