当我将ls
命令与option一起使用时-l
,第一个字母字符串给出有关每个文件的信息,而在该字符串中的第一个字母给出文件的类型。(d
=目录,-
=标准文件,l
=链接等)
如何根据第一个字母过滤文件?
当我将ls
命令与option一起使用时-l
,第一个字母字符串给出有关每个文件的信息,而在该字符串中的第一个字母给出文件的类型。(d
=目录,-
=标准文件,l
=链接等)
如何根据第一个字母过滤文件?
Answers:
如果要显示所有输出,但在一起列出了相似类型的文件,则可以在每行的第一个字符上对输出进行排序:
ls -l | sort -k1,1
该命令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. [...]
ls -l | sort
这将根据每个结果的字母顺序对结果进行排序。如果第一个字符是您想要的条件,就是这样。如果仅需要文件名,则可以尝试:
ls -l | sort | cut -f 2 -d ' '
或类似的命令(该命令使用空格定界符进行排序,然后分割每行,然后返回第二组。