bash Bash脚本将目录的文件读入数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15581893/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Bash Script Reading Files of a directory into Array
提问by Gordon Davisson
I am having trouble reading file into an array in bash.
我在 bash 中将文件读入数组时遇到问题。
I have noticed that people do not recommend using the ls -1 option. Is there a way to get around this?
我注意到人们不推荐使用 ls -1 选项。有没有办法解决这个问题?
回答by Gordon Davisson
The most reliable way to get a list of files is with a shell wildcard:
获取文件列表的最可靠方法是使用 shell 通配符:
# First set bash option to avoid
# unmatched patterns expand as result values
shopt -s nullglob
# Then store matching file names into array
filearray=( * )
If you need to get the files somewhere other than the current directory, use:
如果您需要在当前目录以外的其他地方获取文件,请使用:
filearray=( "$dir"/* )
Note that the directory path should be in double-quotes in case it contains spaces or other special characters, but the *cannot be or it won't be expanded into a file list. Also, this fills the array with the paths to the files, not just the names (e.g. if $diris "path/to/directory", filearray will contain "path/to/directory/file1", "path/to/directory/file2", etc). If you want just the file names, you can trim the path prefixes with:
请注意,目录路径应该用双引号引起来,以防它包含空格或其他特殊字符,但*不能或不会扩展为文件列表。此外,这会用文件的路径填充数组,而不仅仅是名称(例如,如果$dir是“path/to/directory”,filearray 将包含“path/to/directory/file1”、“path/to/directory/file2” “, 等等)。如果您只想要文件名,则可以使用以下命令修剪路径前缀:
filearray=( "$dir"/* )
filearray=( "${filearray[@]##*/}" )
If you need to include files in subdirectories, things get a bit more complicated; see this previous answer.
如果您需要在子目录中包含文件,事情会变得有点复杂;看到这个以前的答案。

