简体   繁体   中英

Produce a custom nicer ls-l output using awk

I am trying to write a awk script to produce a custom output from ls -l something like this:


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.
...

I find the most difficult task is to parse the first column $1 to get the permission and file/directory. Can you give me a hint how to solve this?

Sincerely, Kohn

Don't parse ls use 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM