Bash: How to print the filename of the nth file in a folder

Deadly 提交于 2019-12-22 10:07:21

问题


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]}"

回答1:


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]}"

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"/* )


来源:https://stackoverflow.com/questions/25631016/bash-how-to-print-the-filename-of-the-nth-file-in-a-folder

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!