当我使用ls
带有选项的命令时-l
,第一个字母字符串给出有关每个文件的信息,该字符串中的第一个字母给出文件的类型。 (d
=目录、-
=标准文件、l
=链接等)
如何根据第一个字母过滤文件?
答案1
grep
您可以使用以下方式过滤除目录之外的所有内容:
ls -l | grep '^d'
表示^
该模式位于该行的开头。如果适用,请替换d
为-
、等。l
您当然可以使用其他命令直接搜索特定类型(例如find . -maxdepth 1 -type d
)或ls -l | sort
根据第一个字符将类似类型分组在一起,但如果您想过滤,则应该grep
仅从输出中选择适当的行。
答案2
如果要显示所有输出,但将类似类型的文件列在一起,则可以按每行的第一个字符对输出进行排序:
ls -l | sort -k1,1
答案3
该命令ls
正在处理文件名,它们记录在目录数据结构中。所以它并不真正关心文件本身,包括文件的“类型”。
更适合工作的命令实际文件,不仅仅是它的名字,是find
。它有一个选项可以直接回答您有关如何过滤文件类型列表的问题。
这给出了类似于以下内容的当前目录的列表ls -l
:
find . -maxdepth 1 -ls
默认情况下,find
以递归方式列出目录,通过将搜索深度限制为 1 来禁用该功能。您可以省略.
,但我将其包含在内以显示需要在选项之前列出的目录。
使用-type
,您可以按文件类型进行过滤,文件类型表示为f
或d
为纯文件或目录:
find . -maxdepth 1 -type d -ls
还有其他过滤器值-type
,尤其l
是符号链接。
请注意符号链接的复杂化:在这种情况下,文件有两种类型:l
,表示符号链接,以及类似 的内容f
,表示链接到的文件的类型。有一些选项可以指定如何处理该问题,因此您可以进行选择。
从man find
:
-type c
File is of type c:
b block (buffered) special
c character (unbuffered) special
d directory
p named pipe (FIFO)
f regular file
l symbolic link; this is never true if the -L option
or the -follow option is in effect, unless the sym‐
bolic link is broken. If you want to search for
symbolic links when -L is in effect, use -xtype.
s socket
D door (Solaris)
与符号链接的处理相关:
-xtype c
The same as -type unless the file is a symbolic link. For
symbolic links: if the -H or -P option was specified, true
if the file is a link to a file of type c; if the -L option
has been given, true if c is `l'. In other words, for sym‐
bolic links, -xtype checks the type of the file that -type
does not check.
和
-P Never follow symbolic links. This is the default behav‐
iour. When find examines or prints information a file, and
the file is a symbolic link, the information used shall be
taken from the properties of the symbolic link itself.
-L Follow symbolic links. When find examines or prints infor‐
mation about files, the information used shall be taken
from the properties of the file to which the link points,
not from the link itself (unless it is a broken symbolic
link or find is unable to examine the file to which the
link points). Use of this option implies -noleaf. If you
later use the -P option, -noleaf will still be in effect.
If -L is in effect and find discovers a symbolic link to a
subdirectory during its search, the subdirectory pointed to
by the symbolic link will be searched.
When the -L option is in effect, the -type predicate will
always match against the type of the file that a symbolic
link points to rather than the link itself (unless the sym‐
bolic link is broken). Using -L causes the -lname and
-ilname predicates always to return false.
-H Do not follow symbolic links, except while processing the
command line arguments. [...]
答案4
如果您最关心从其他文件类型排序文件夹,您可以选择
ls --group-directories-first
否则,我认为你必须通过排序或通过 grep 从 ls -l 输出管道,如 Anthon 所回答