![如何从命令行显示子目录中的项目数](https://linux22.com/image/1166576/%E5%A6%82%E4%BD%95%E4%BB%8E%E5%91%BD%E4%BB%A4%E8%A1%8C%E6%98%BE%E7%A4%BA%E5%AD%90%E7%9B%AE%E5%BD%95%E4%B8%AD%E7%9A%84%E9%A1%B9%E7%9B%AE%E6%95%B0.png)
答案1
这里有一个你可以使用的 shell 函数。只需将以下几行添加到你的~/.bashrc
:
lsc(){
## globs that don't match should expand to a null string
shopt -s nullglob
## If no arguments were given use the current dir
if [[ $# -eq 0 ]]; then
targets="."
## Otherwise, use whatever was given
else
targets=($@)
fi
## iterate over the arguments given
for target in "${targets[@]}"; do
## get the contents of the target
contents=("$target"/*)
## iterate over the contents
for thing in "${contents[@]}"; do
## If this one is a directory
if [[ -d "$thing" ]]; then
## collect the directory's contents
count=("$thing"/*)
## Print the dir's name (with a '/' at the end)
## and the number of items found in it
printf "%s/ (%s)\n" "$thing" "${#count[@]}"
else
## If this isn't a dir, just print the name
printf "%s\n" "$thing"
fi
done
done
}
然后打开一个新终端并运行:
lsc /path/to/dir
例如,给定以下目录(\012
名称中有换行符):
$ tree
.
├── a bad one
│ └── file 1
├── a bad worse\012one
│ └── file 1 \012two
├── dir1
│ └── file
├── dir2
│ ├── file1
│ └── file2
├── dir3
│ ├── file1
│ ├── file2
│ └── file3
├── dir4
│ └── dir
├── empty_dir
8 directories, 7 files
您将获得:
$ lsc
./a bad one/ (1)
./a bad worse
one/ (1)
./dir1/ (1)
./dir2/ (2)
./dir3/ (3)
./dir4/ (1)
./empty_dir/ (0)
./mp3/ (1)
这种方法的主要优点是:
您可以在多个目录上运行它:
lsc /path/to/dir /path/to/dir2 ... /path/to/dirN
或者在当前版本上:
lsc
它可以处理任意文件和目录名,甚至包含空格或换行符,如上所示。