# tree system/
system/
├── cat1
│ └── id1
├── cat5
│ └── id42
├── cat20
│ └── 59593
└── mumbry
└── 3939
4 directories, 4 files
#
如何获取目录名称和文件名?如果可能的话,如何在一个for循环中使用目录和文件名?
答案 0 :(得分:3)
如果要遍历子目录和文件名,简单的wildcard expansion会生成一个列表。
cd system
for file in */*; do
echo "$file"
done
如果要将它们拆分为目录和基本名称,shell中有内置的text extraction facilities:
for file in */*; do
echo "Directory: ${file%/*}"
echo "Basename: ${file#*/}"
done
答案 1 :(得分:0)
@tripleee中的目录和Basename替换在我的bash 4.2.25中不起作用,正确的for循环是:
for file in */*; do
# the match start from the end so you must invert the regexp
echo "Directory: ${file%/*}"
# we must remove all the matches, not only the first
echo "Basename: ${file##*/}"
done