Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/unix/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在shell脚本中打印文件的时间_Shell_Unix - Fatal编程技术网

在shell脚本中打印文件的时间

在shell脚本中打印文件的时间,shell,unix,Shell,Unix,我正在尝试使用以下shell脚本打印所有文件的时间。但我发现并非总是字节42到46是时间,因为用户名和其他详细信息中的字节较多/较少会导致时间发生变化。还有别的办法打发时间吗 #!/bin/sh for file in `ls ` do #echo `ls -l $file` echo `ls -l $file | cut -b 42-46` done 使用awk 试试ls-l|awk'{print$6$7$8}' 这将打印ls-l的第6、第7和第8个字段,并用空格分隔 如果字

我正在尝试使用以下shell脚本打印所有文件的时间。但我发现并非总是字节42到46是时间,因为用户名和其他详细信息中的字节较多/较少会导致时间发生变化。还有别的办法打发时间吗

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

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

这将打印ls-l的第6、第7和第8个字段,并用空格分隔


如果字段不同,请更改数字以调整哪些字段。

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

您可能也想添加间距
ls-l|awk'{print$6”“$7”“$8}'
。如果我对日期做同样的操作,我会得到一个错误。echo
date | awk'(打印“$1”)
。很好。但我使用的是切割,因为日期的输出是小时、分钟和秒,而as-l只给出小时和分钟。感谢Daveh,如果文件名包含空格、换行符等,此操作将失败。我喜欢
stat
。请阅读关于使用自定义日期格式与
ls
,或Perl运算符
-a、
-C
-M`。另外,请参阅
-t
选项以修改
%y
打印的时间所使用的格式。