当我使用ls
带有选项的命令时-l
,第一个字母字符串给出了每个文件的信息,这个字符串中的第一个字母给出了文件的类型。(d
= 目录、-
= 标准文件、l
= 链接等)
如何根据第一个字母过滤文件?
Ant*_*hon 14
您可以使用grep
这种方式过滤除目录之外的所有内容:
ls -l | grep '^d'
Run Code Online (Sandbox Code Playgroud)
所述^
指示图案是在该行的开头。替换d
为-
、l
等,视情况而定。
您当然可以使用其他命令直接搜索特定类型(例如find . -maxdepth 1 -type d
)或使用ls -l | sort
基于此第一个字符将相似类型组合在一起,但如果您想过滤,您应该使用grep
仅从输出中选择适当的行。
Jos*_* R. 13
如果要显示所有输出但将类似类型的文件列在一起,则可以按每行的第一个字符对输出进行排序:
ls -l | sort -k1,1
Run Code Online (Sandbox Code Playgroud)
Vol*_*gel 10
该命令ls
正在处理记录在目录数据结构中的文件名。所以它并不真正关心文件本身,包括文件的“类型”。
更适合处理实际文件的命令是find
. 它有一个选项可以直接回答您关于如何过滤文件类型列表的问题。
这给出了类似于以下内容的当前目录列表ls -l
:
find . -maxdepth 1 -ls
Run Code Online (Sandbox Code Playgroud)
默认情况下,find
递归列出目录,通过将搜索深度限制为 1 来禁用它。您可以省略.
,但我将其包含在内以显示需要在选项之前列出的目录。
有了-type
,您可以按文件类型,其表示为过滤f
或d
对普通文件或目录:
find . -maxdepth 1 -type d -ls
Run Code Online (Sandbox Code Playgroud)
有其他过滤器值-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)
Run Code Online (Sandbox Code Playgroud)
与符号链接的处理相关:
-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.
Run Code Online (Sandbox Code Playgroud)
和
-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. [...]
Run Code Online (Sandbox Code Playgroud)