1

我正在尝试编写一个 awk 脚本来从 ls -l 生成自定义输出,如下所示:


File xxx.txt has size of 100 blocks, was last modified on July 3 2013, is owned by Kohn. The user has read permission, has write permission and has execute permission.

Dir abc has size of 200 blocks, was last modified on July 1 2013, is owned by Kohn. The user has read permission, does not have write permission and has execute permission.
...

我发现最困难的任务是解析第一列 $1 以获取权限和文件/目录。你能给我一个提示如何解决这个问题吗?

真诚的,科恩

4

1 回答 1

2

不要解析 ls使用stat

#!/bin/bash

myls() {
    local filetype=$(stat -c "%F" "$1")
    local format="${filetype^} %n has size of %b blocks, "
    format+="was last modified on $(date -d "@$(stat -c "%Y" "$1")" "+%B %e, %Y"), "
    format+="is owned by %U. "
    format+="$(permissions "$1")"
    stat -c "$format" "$1"
}

permissions() {
    local user_perms=$(stat -c "%A" "$1")
    local string="The user "
    string+="$(has ${user_perms:1:1} r) read permission, "
    string+="$(has ${user_perms:2:1} w) write permission, "
    string+="$(has ${user_perms:3:1} x) execute permission."
    echo "$string"
}
has() { [[ $1 == $2 ]] && echo "has" || echo "does not have"; }

for file; do
    myls "$file"
done
于 2013-07-04T19:53:52.513 回答