Bash:如何在文件夹中打印第n个文件的文件名 [英] Bash: How to print the filename of the nth file in a folder

查看:31
本文介绍了Bash:如何在文件夹中打印第n个文件的文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在文件夹的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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆