shell 如何在Linux Bash中将ls分配给数组?

xu3bshqb  于 11个月前  发布在  Shell
关注(0)|答案(4)|浏览(176)
array=${ls -d */}
echo ${array[@]}

字符串
我有三个目录:wweeqq。我希望它们在一个数组中,然后打印数组。

chhkpiq4

chhkpiq41#

会这么

array=($(ls -d */))

字符串
编辑:请参阅Gordon Davisson's solution以获得更一般的答案(即,如果您的文件名包含特殊字符)。此答案仅是语法更正。

a7qyws3x

a7qyws3x2#

只要有可能,就应该避免解析ls的输出(参见Greg's wiki on the subject)。基本上,如果任何一个文件名中有有趣的字符,ls的输出都将是模糊的。这通常也是浪费时间。在这种情况下,当您执行ls -d */时,发生的情况是,shell将*/展开为子目录列表(这正是您想要的),将该列表作为参数传递给ls -dls -d查看每个列表,说“是的,that's a directory all right”并将其打印出来(格式不一致,有时甚至不明确)。ls命令没有做任何有用的事情!
好吧,好吧,它做了一件有用的事情:如果没有子目录,*/将保持原样,ls将查找名为“"的字符串,但没有找到它,打印一条错误消息,表明它不存在(到stderr),not 打印“/”(到stdout)。
创建一个数组名的更简洁的方法是使用glob(*/)* 而不将其传递给ls。但是为了避免在没有实际子目录的情况下将“*/”放入数组中,您应该首先设置nullglob(再次,参见Greg's wiki):

shopt -s nullglob
array=(*/)
shopt -u nullglob # Turn off nullglob to make sure it doesn't interfere with anything later
echo "${array[@]}"  # Note double-quotes to avoid extra parsing of funny characters in filenames

字符串
如果你想在没有子目录的情况下打印错误消息,你最好自己做:

if (( ${#array[@]} == 0 )); then
    echo "No subdirectories found" >&2
fi

6psbrbz9

6psbrbz93#

这将逐行打印这些目录中的文件。

array=(ww/* ee/* qq/*)
printf "%s\n" "${array[@]}"

字符串

aoyhnmkz

aoyhnmkz4#

试试这个..

filesArray=(*.mp4)
filesCount=${#filesArray[@]}
for (( i=0;i<$filesCount;i++)); do
    singleFile="${filesArray[$i]}"
    #here I replace ALL the spaces in the file's name, by underscores.
    trimmed=${singleFile// /\_}
    mv "${singleFile}" "${trimmed}"
    echo "renamed ${singleFile} as ${trimmed} !"
done

字符串
请改善我的回答,如果有任何错误..!

相关问题