How do I capture the output from the ls or find command to store all file names in an array?

血红的双手。 提交于 2019-11-29 10:41:30

问题


Need to process files in current directory one at a time. I am looking for a way to take the output of ls or find and store the resulting value as elements of an array. This way I can manipulate the array elements as needed.


回答1:


To answer your exact question, use the following:

arr=( $(find /path/to/toplevel/dir -type f) )

Example

$ find . -type f
./test1.txt
./test2.txt
./test3.txt
$ arr=( $(find . -type f) )
$ echo ${#arr[@]}
3
$ echo ${arr[@]}
./test1.txt ./test2.txt ./test3.txt
$ echo ${arr[0]}
./test1.txt

However, if you just want to process files one at a time, you can either use find's -exec option if the script is somewhat simple, or you can do a loop over what find returns like so:

while IFS= read -r -d $'\0' file; do
  # stuff with "$file" here
done < <(find /path/to/toplevel/dir -type f -print0)



回答2:


for i in `ls`; do echo $i; done;

can't get simpler than that!

edit: hmm - as per Dennis Williamson's comment, it seems you can!

edit 2: although the OP specifically asks how to parse the output of ls, I just wanted to point out that, as the commentators below have said, the correct answer is "you don't". Use for i in * or similar instead.




回答3:


You actually don't need to use ls/find for files in current directory.

Just use a for loop:

for files in *; do 
    if [ -f "$files" ]; then
        # do something
    fi
done

And if you want to process hidden files too, you can set the relative option:

shopt -s dotglob

This last command works in bash only.




回答4:


Depending on what you want to do, you could use xargs:

ls directory | xargs cp -v dir2

For example. xargs will act on each item returned.



来源:https://stackoverflow.com/questions/4678418/how-do-i-capture-the-output-from-the-ls-or-find-command-to-store-all-file-names

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