Bash:如何在文件夹中打印第n个文件的文件名 [英] Bash: How to print the filename of the nth file in a folder
问题描述
我在文件夹的773rd文件中遇到解析错误.可以在bash中打印文件名吗?
I'm getting a parsing error in the 773rd file of a folder. Is it possible to print the name of the file in bash?
我尝试使用它来打印它,但是它返回一个空白.
I've tried using this to print it but it returns a blank.
files=(/path/to/files)
echo "${files[773]}"
推荐答案
非常接近,但是您实际上需要做一个glob将列表收集到数组中,而不是仅包含一个元素的列表(父目录):
Very close, but you need to actually do a glob to collect the list into your array, rather than having a list with only one element (the parent directory):
files=( /path/to/files/* )
echo "${files[772]}"
如果您要以一种易于理解的方式表示不可打印字符的方式来表示文件名,则 echo
是错误的工具.相反,请考虑:
If you want to represent your filename in a way that represents nonprintable characters in a human-readable way, echo
is the wrong tool. Instead, consider:
printf '%q\n' "${files[772]}"
如果您的路径来自变量,请确保引用其扩展名,但不是全局字符:
If your path is coming from a variable, be sure to quote its expansion, but not the glob character:
files=( "$dir"/* )
这篇关于Bash:如何在文件夹中打印第n个文件的文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!