How to store directory files listing into an array?

前端 未结 5 633
清酒与你
清酒与你 2021-01-30 13:10

I\'m trying to store the files listing into an array and then loop through the array again. Below is what I get when I run ls -ls command from the console.

相关标签:
5条回答
  • 2021-01-30 13:31

    I'd use

    files=(*)
    

    And then if you need data about the file, such as size, use the stat command on each file.

    0 讨论(0)
  • This might work for you:

    OIFS=$IFS; IFS=$'\n'; array=($(ls -ls)); IFS=$OIFS; echo "${array[1]}"
    
    0 讨论(0)
  • 2021-01-30 13:36

    Try with:

    #! /bin/bash
    
    i=0
    while read line
    do
        array[ $i ]="$line"        
        (( i++ ))
    done < <(ls -ls)
    
    echo ${array[1]}
    

    In your version, the while runs in a subshell, the environment variables you modify in the loop are not visible outside it.

    (Do keep in mind that parsing the output of ls is generally not a good idea at all.)

    0 讨论(0)
  • 2021-01-30 13:38

    Running any shell command inside $(...) will help to store the output in a variable. So using that we can convert the files to array with IFS.

    IFS=' ' read -r -a array <<< $(ls /path/to/dir)
    
    0 讨论(0)
  • 2021-01-30 13:40

    Here's a variant that lets you use a regex pattern for initial filtering, change the regex to be get the filtering you desire.

    files=($(find -E . -type f -regex "^.*$"))
    for item in ${files[*]}
    do
      printf "   %s\n" $item
    done
    
    0 讨论(0)
提交回复
热议问题