我有一个目录路径,其中有多个文件和目录。
我想使用基本的bash脚本创建仅包含目录列表的数组。
假设我有一个目录路径:
/my/directory/path/
$ls /my/directory/path/
a.txt dirX b.txt dirY dirZ
现在,我想只用目录(即arr[]
,dirX
和dirY
填充名为dirZ
的数组。
有一个post,但与我的要求无关。
任何帮助将不胜感激!
答案 0 :(得分:2)
尝试一下:
#!/bin/bash
arr=(/my/directory/path/*/) # This creates an array of the full paths to all subdirs
arr=("${arr[@]%/}") # This removes the trailing slash on each item
arr=("${arr[@]##*/}") # This removes the path prefix, leaving just the dir names
与基于ls
的答案不同,它不会被包含空格,通配符等的目录名称所混淆。
答案 1 :(得分:1)
尝试:
shopt -s nullglob # Globs that match nothing expand to nothing
shopt -s dotglob # Expanded globs include names that start with '.'
arr=()
for dir in /my/directory/path/*/ ; do
dir2=${dir%/} # Remove the trailing /
dir3=${dir2##*/} # Remove everything up to, and including, the last /
arr+=( "$dir3" )
done