randeepsp
randeepsp

Reputation: 3842

Printing the time of files in shell script

I am trying to print the time of all the files using the following shell script. But I see that not always bytes 42 to 46 is the time, as it changes due to more/less bytes in username and other details. Is there another way to fetch the time?

#!/bin/sh
for file in `ls `
do
    #echo `ls -l $file`
    echo `ls -l $file | cut -b 42-46`
done

Upvotes: 2

Views: 5044

Answers (2)

Jonathan Leffler
Jonathan Leffler

Reputation: 753475

The output from ls varies depending on the age of the files. For files less than about 6 months old, it is the month, day, time (in hours and minutes); for files more than about 6 months old, it prints the month, day, year.

The stat command can be used to get more accurate times.

For example, to print the time of the last modification and file name of some text files, try:

stat -c '%y %n' *.txt

From the manual:

   %x     Time of last access
   %X     Time of last access as seconds since Epoch
   %y     Time of last modification
   %Y     Time of last modification as seconds since Epoch
   %z     Time of last change
   %Z     Time of last change as seconds since Epoch

man stat

Upvotes: 2

daveh
daveh

Reputation: 3696

Use awk.

Try ls -l | awk '{ print $6 $7 $8}'

This will print the 6th, 7th and 8th fields of ls -l split by whitespace

If the fields are different for you change the numbers to adjust which fields.

Upvotes: 5

Related Questions