解析“ls -l”的输出结果以获取QNX上的用户和组

1 ls shell sed qnx

我正在使用 QNX。

我有以下输出ls -l

drwxr-xr-x   2 root      root           4096 Jul 26  2021 bin
Run Code Online (Sandbox Code Playgroud)

由此,我想使用sed提取用户和组,并将这些字符串放入 shell 变量中。

我无权访问stat命令。

Sté*_*las 5

如果您的 shell 是 POSIX shell,并且用户名和组名不包含空格字符,您可以使用 split+glob 运算符(当您在列表上下文中不加引号地保留参数扩展、命令替换或算术扩展时隐式调用):

IFS=' ' # split on space only
set -o noglob # disable the glob part
output=$(LC_ALL=C ls -Lld bin) || exit # exit if bin can't be stat()ed.

set -- $output # split+glob $output and assign result to positional parameters

mode=$1 # could also contain +, @... to specify system-dependent extra
        # information such as the presence of ACLs or extended attributes

links=$2 user=$3 group=$4 size=$5
Run Code Online (Sandbox Code Playgroud)

如果您不能保证用户名和组名不包含空格字符,您可以使用ls -n代替,ls -l然后您将获得 uid 和 gid $user$group这可能足以满足您的需要。

使用sed,您可以使用它来解析输出的第一行ls并生成设置变量的 shell 代码:

get_credentials() {
  eval "$(
    sp=' \{1,\}' nsp='[^ ]\{1,\}'
    LC_ALL=C ls -Lld -- "${1?}" |
      LC_ALL=C sed -n "
        /^$nsp$sp$nsp$sp\($nsp\)$sp\($nsp\).*$/ {
          s//\1 \2/
          s/'/'\\\\''/g
          s/\($nsp\) \($nsp\)/user='\1' group='\2' ||/p
        }
        q"
    ) false"
}
Run Code Online (Sandbox Code Playgroud)

用作:

get_credentials bin || exit
printf 'The %s name is: "%s"\n' user  "$user" \
                                group "$group"
Run Code Online (Sandbox Code Playgroud)

这将eval审视你们的user='the-user' group='the-group' || false壳代码(或user='o'\''connor'...用于o'connor例如)如果用户名和组名可以从第一行中提取ls输出,或 false以其他方式。