【问题标题】:extract the starting character of ls -l output for a file in unix在 unix 中提取文件的 ls -l 输出的起始字符
【发布时间】:2016-09-17 17:16:47
【问题描述】:

以下是文件名:

-rwxrwxrwx 1 user1 users 268 Sep 16 18:06 script

在这里grep第一个字符的命令应该是什么?

基于此,我想判断该项目是文件、目录还是软链接。

我们可以使用通配符“^”来获取此信息吗?

【问题讨论】:

  • 对于既不是目录、FIFO、符号链接或设备的文件,ls -l 输出的第一个字符并不总是-——这在很大程度上取决于您的操作系统的扩展名。 POSIX 确实 指定第一个字符指定“文件类型”,并为几种特定类型指定特定字符,但也明确指出“实现可以将其他字符添加到此列表中以表示其他实现定义的文件类型。”
  • 顺便说一句,^ 实际上不是通配符——而通配符完全匹配任何字符,^(在正则表达式中)匹配零个字符(并且仅在字符串的前面) .因此,您可以使用 ^. 匹配字符串前面的单个字符——在这种情况下,. 是使用的通配符,^ 限制匹配的位置——但没有太多理由在这里这样做。
  • 对。 wrt ^ - s/通配符/元字符/。

标签: bash shell grep wildcard


【解决方案1】:

这是判断某个东西是否是符号链接的错误方法; you should never parse the output of ls, which is meant for human consumption only。相反,请使用 test 原语:

for name in *; do
  if   test -L "$name"; then echo "symlink:           $name"
  elif test -f "$name"; then echo "regular file:      $name"
  elif test -d "$name"; then echo "directory:         $name"
  elif test -b "$name"; then echo "block device:      $name"
  elif test -c "$name"; then echo "character device:  $name"
  elif test -p "$name"; then echo "named pipe (FIFO): $name"
  elif test -S "$name"; then echo "socket:            $name"
  else                       echo "other:             $name"
  fi
done

上面也可以写成[ -L "$name" ][ -f "$name" ]等;就像有一个名为test 的shell 内置命令和一个名为/usr/bin/test 的可执行文件一样,还有一个名为[ 的shell 内置命令和一个类似/usr/bin/[ 的可执行文件(其行为方式完全相同,除了要求它的最后一个参数是])。


回答您的字面问题,与解决如何最好地解决您的实际/潜在问题:

一旦你在shell中的字符串中有内容,你可以执行参数扩展来获取第一个字符:

s=abc # or s=$(...some command here...), or so forth
echo "${s:0:1}" # this returns "a"

要获取流的第一个字符(例如来自管道命令的标准输出),您可以简单地使用head -c 1

echo "abc" | head -c 1 # this also returns "a"; echo can be replaced with any other command

【讨论】:

    猜你喜欢
    • 2012-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-07
    • 1970-01-01
    • 2013-11-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多