UNIX stat time format

2020-06-12 04:27发布

Is it possible to format the time output of stat? I am using

stat -c '%n %A %z' $filename

in a bash script, but its time format is not what I want. Is it possible to change this format in the command, or would I have to manually do it later?

An example output follows:

/lib drwxr-xr-x 2010-11-15 04:02:38.000000000 -0800

2条回答
Root(大扎)
2楼-- · 2020-06-12 05:10

You can simply strip of the decimal portion like this:

stat -c '%n %A %z' "$filename" | sed 's/\(:[0-9]\{2\}\)\.[0-9]* /\1 /'

Edit:

Here's another way to truncate the decimal portion:

stat -c '%n %A %.19z' "$filename"

This depends on the date being 19 characters long: 2010-11-15 04:02:38

查看更多
甜甜的少女心
3楼-- · 2020-06-12 05:20

You could try something like:

date -d "1970-01-01 + $(stat -c '%Z' $filename ) secs"

Which gives you only the date. You can format the date using date's formatting options (see man date), for example:

date -d "1970-01-01 + $(stat -c '%Z' $filename ) secs" '+%F %X'

This doesn't give you the name and permissions but you may be able to do that like:

echo "$(stat -c '%n %A' $filename) $(date -d "1970-01-01 + $(stat -c '%Z' $filename ) secs"  '+%F %X')"
查看更多
登录 后发表回答