Linux-Ubuntu / 我想查看目录下的文件以及文件数量

Linux-Ubuntu / 我想查看目录下的文件以及文件数量

我想查看目录(桌面)中的文件以及 shell 脚本中的文件数量。我该怎么做?

我发现了这个,对吗?

#!/bin/bash

echo "Files:"
find . -maxdepth 1 -type f

echo "Number of files:"
ls -Anq | grep -c '^-'

答案1

发现是正确的,但是你不应该解析ls,甚至找不到文件的数量。既然你有 GNU find,请选择

#!/bin/bash
echo "Files:"
find . -maxdepth 1 -type f

echo "Number of files:"
find . -maxdepth 1 -type f -printf . | wc -c

第二个为每个文件find打印 a .,然后wc计算点数。

答案2

find这里就没有必要了

#!/bin/bash

# nullglob: make patterns that don't match expand to nothing
# dotglob: also expand patterns to hidden names
shopt -s nullglob dotglob

names=( * )    # all names in the current directory
regular_files=()

# separate out regular files into the "regular_files" array
for name in "${names[@]}"; do
    # the -L test is true for symbolic links, we want to skip these
    if [[ -f $name ]] && [[ ! -L $name ]]; then
        regular_files+=( "$name" )
    fi
done

printf 'There are %d names (%d regular files)\n' "${#names[@]}" "${#regular_files[@]}"
printf 'The regular files are:\n'
printf '\t%s\n' "${regular_files[@]}"

或者,与zsh,

#!/bin/zsh

# "ND" corresponds to setting nullglob and dotglob for the pattern
names=( *(ND) )
regular_files=( *(.ND) )   # "." selects only regular files

printf 'There are %d names (%d regular files)\n' "${#names[@]}" "${#regular_files[@]}"
printf 'The regular files are:\n'
printf '\t%s\n' "${regular_files[@]}"

相关内容