在Linux机器上,我希望遍历一个文件夹层次结构,并获得其中所有不同文件扩展名的列表。

从外壳中实现这一点的最佳方法是什么?


当前回答

接受的答案使用REGEX,你不能用REGEX创建别名命令,你必须把它放在一个shell脚本中,我使用亚马逊Linux 2,并做了以下工作:

我把接受的答案代码放入一个文件,使用: Sudo vim find.sh

添加以下代码:

find ./ -type f | perl -ne 'print $1 if m/\.([^.\/]+)$/' | sort -u

输入::wq保存文件。

Sudo vim ~/.bash_profile 别名getext = "。/道路/ /你/ find.sh” : wq ! . ~ / . bash_profile

其他回答

找到每一个点,只显示后缀。

find . -type f -name "*.*" | awk -F. '{print $NF}' | sort -u

如果你知道所有后缀有3个字符,那么

find . -type f -name "*.???" | awk -F. '{print $NF}' | sort -u

或使用sed显示所有1到4个字符的后缀。将{1,4}更改为您希望在后缀中使用的字符范围。

find . -type f | sed -n 's/.*\.\(.\{1,4\}\)$/\1/p'| sort -u

在Python中,为非常大的目录使用生成器,包括空白扩展名,并获取每个扩展名出现的次数:

import json
import collections
import itertools
import os

root = '/home/andres'
files = itertools.chain.from_iterable((
    files for _,_,files in os.walk(root)
    ))
counter = collections.Counter(
    (os.path.splitext(file_)[1] for file_ in files)
)
print json.dumps(counter, indent=2)

我认为最简单直接的方法是

for f in *.*; do echo "${f##*.}"; done | sort -u

它是根据克里斯托夫的第三种方法改进的。

我发现它简单快捷……

   # find . -type f -exec basename {} \; | awk -F"." '{print $NF}' > /tmp/outfile.txt
   # cat /tmp/outfile.txt | sort | uniq -c| sort -n > tmp/outfile_sorted.txt

接受的答案使用REGEX,你不能用REGEX创建别名命令,你必须把它放在一个shell脚本中,我使用亚马逊Linux 2,并做了以下工作:

我把接受的答案代码放入一个文件,使用: Sudo vim find.sh

添加以下代码:

find ./ -type f | perl -ne 'print $1 if m/\.([^.\/]+)$/' | sort -u

输入::wq保存文件。

Sudo vim ~/.bash_profile 别名getext = "。/道路/ /你/ find.sh” : wq ! . ~ / . bash_profile