简体   繁体   English

将ls输出转换为数组

[英]Convert ls Output Into an Array

I want to put the output of an ls into an array so I can loop through it and eventually use a entry the user will specify. 我想将ls的输出放入一个数组中,这样我就可以循环遍历它,并最终使用用户将指定的条目。

What I did is the following 我所做的是以下

SETUPS="$(ls)"
IFS=$' ' read -rd '' setup <<<"$SETUPS"

when I run echo $setup[0] it will already show me all the files that are present 当我运行echo $setup[0] ,它将向我显示所有存在的文件
while I should be able to run echo $setup[0] and only get the first entry. 而我应该能够运行echo $setup[0]并仅获得第一个条目。

Could anyone tell me what I'm doing wrong here? 有人可以告诉我我在做什么错吗?

I already tried SETUPS="$(ls -1)" to seperate it with IFS=$'\\n' read -rd '' setup <<<"$SETUPS" but that didn't work either. 我已经尝试过SETUPS="$(ls -1)"来将其与IFS=$'\\n' read -rd '' setup <<<"$SETUPS"分开, IFS=$'\\n' read -rd '' setup <<<"$SETUPS"但这也不起作用。

Right now I'm looping through it like this 现在我正在像这样遍历它

n=0
for i in `echo ${setup} | tr "," " "` 
   do
   n=$((n+1))
   echo $n". $i"
done

which works to echo every entry with a number in front of it but I can't possibly select an entry out of there since every value seems to be stored as 1 value 它的工作原理是回显每个条目前面有一个数字的条目,但由于每个值似乎都存储为1值,所以我不可能从那里选择一个条目

If you want to get all the files in this directory in an array you can use globbing: 如果要获取数组中此目录中的所有文件,则可以使用遍历:

files=(*)
printf '%s\n' "${files[@]}"

will store all the files matched by the glob in the array files and then you can print them with printf if you so desire, or do whatever else you want with looping over the array. 将与glob匹配的所有文件存储在数组files ,然后您可以根据需要使用printf打印它们,或者通过循环遍历数组进行其他操作。

n=0
for current in "${files[@]}"; do
    n=((n+1))
    printf '%s %s\n' "$n" "$current"
done

You don't even need to store it in an array in the middle if you don't need it for some other purpose: 如果不需要将其存储在中间的数组中,则无需将其用于其他用途:

for current in *; do

works just fine 效果很好

See, why not parse output of ls , but rather use a proper while loop with process-substitution (<()). 请参阅,为什么不解析ls输出 ,而是使用带有进程替换(<())的适当while循环

#!/bin/bash

while IFS= read -r -d '' file
do
    printf "%s\n" "${file#*/}" 
done < <(find . -maxdepth 1 -mindepth 1 -type f -print0)

(or) if you are interested in storing the folder contents in an array (或)如果您有兴趣将文件夹内容存储在数组中

fileContents=()
while IFS= read -r -d '' file
do
    fileContents+=("${file#*/}") 
done < <(find . -maxdepth 1 -mindepth 1 -type f -print0)

printf "%s\n" "${fileContents[@]}"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM