2012-09-05 73 views
1

我正在嘗試使用以下shell腳本打印所有文件的時間。但是我發現並不總是字節42到46是時間,因爲它由於用戶名和其他細節中的更多/更少的字節而變化。是否有另一種獲取時間的方法?在shell腳本中打印文件的時間

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

閱讀[我答案](http://superuser.com/questions/447684/fastest-way-to-get-creation-and-last-modification-times-of-a-lot-of-files/469902#469902)至[最快方式獲得創造和最後修改時間的很多文件](http://superuser.com/questions/447684/fastest-way-to-get-creation-and-last-modification-times-of-a-lot-of-files)關於使用自定義日期格式'ls',或Perl運算符'-A,'-C'和'-M'。 –

回答

4

使用awk。

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

這將空白

打印6,LS的第七和第八場-l分裂如果您更改數字要調整的字段的字段是不同的。

+0

您可能想要添加間距'ls -l | awk'{print $ 6''$ 7「'$ 8}''。 – alex

+0

工作得很好。謝謝 – randeepsp

+0

如果我用日期做同樣的事情,我得到一個錯誤。 echo'date | awk'(print'$ 1「)'' – randeepsp

2

ls的輸出取決於文件的年齡。對於少於6個月大的文件,這是月份,日期,時間(以小時和分鐘爲單位);對於大約6個月以上的文件,它會打印月份,日期,年份。

stat命令可用於獲取更準確的時間。

例如,要打印一些文本文件的最後修改和文件名的時候,試試:

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

從手冊:

%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

+0

另外,請參閱'-t'選項來修改用於'%y'打印的時間的格式。 – chepner

+0

謝謝,[史蒂夫](http://stackoverflow.com/users/751863/steve)。 –