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

前端 未结 4 2319
余生分开走
余生分开走 2020-12-30 20:12

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

4条回答
  •  星月不相逢
    2020-12-30 20:30

    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)
    

提交回复
热议问题