shell 脚本 : Count number of files in a particular type extension in single folder

标签 shell sh ls

我是 shell 脚本的新手。 我需要使用 shell 脚本在变量中保存具有特定扩展名(.properties)的文件数。

我用过

ls |grep .properties$ |wc -l

但此命令会打印文件夹中属性文件的数量。如何在变量中分配此值。

我试过了

count=${ls |grep .properties$ |wc -l}

但它显示如下错误:

./replicate.sh: line 57: ${ls |grep .properties$ |wc -l}: bad substitution
  • 这是什么类型的错误?
  • 请任何人帮助我将特定文件的数量保存在变量中以备将来使用。

最佳答案

您使用了错误的括号,它应该是 $()(命令输出替换)而不是 ${}(变量替换)。

count=$(ls -1 | grep '\.properties$' | wc -l)

您还会注意到我使用 ls -1强制每行一个文件,以防您的 ls 不这样做这会自动用于管道,并更改模式以正确匹配 .

如果你使用类似的东西,你也可以完全绕过 grep:

count=$(ls -1 *.properties 2>/dev/null | wc -l)

请注意“邪恶的”文件名,例如那些嵌入换行符的文件名,尽管我的 ls 似乎通过用 ? 字符替换换行符来处理这些问题 -这对于处理文件来说不一定是个好主意,但它可以用来计算它们。

如果您有这样的野兽并且您需要实际的文件名,那么可以使用更好的工具,但它们很少见,您通常不必担心。

关于 shell 脚本 : Count number of files in a particular type extension in single folder,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25740836/

相关文章:

shell脚本中的Mysql数组(Linux)

linux - Linux中execl如何处理 "/bin/sh"?

linux - 在 Linux 中运行 Bash 脚本时出现问题。

python - 从 python 运行 bash 脚本

UNIX 'ls' 命令排除通配符

linux - 交互式 Shell 脚本

regex - egrep 字符串大小写

bash - Jenkins 管道 sh : command not found - are certain commands not available now?

recursion - 是否可以限制 S3 存储桶中递归目录列表的深度?

Python 子进程 Popen : Why does "ls *.txt" not work?