Linux 如何进入每个子目录,列出文件,并为输出提供目录名
我在主目录中有几个子目录。我想进入每个子目录,列出文本文件,并为输出提供子目录的名称Linux 如何进入每个子目录,列出文件,并为输出提供目录名,linux,bash,Linux,Bash,我在主目录中有几个子目录。我想进入每个子目录,列出文本文件,并为输出提供子目录的名称 for d in /home/*/;do cd $d ls *.txt > dir_*_all_txt.list done 我想用子目录的名称替换dir.*。您可以在bash内操作字符串(请参见参数扩展,或者只需在bash手册页中搜索字符串##),以删除最后一个斜杠之前的所有内容: pax> for i in $HOME/tmp* ; do echo $i ${i##*/} ; done /hom
for d in /home/*/;do
cd $d
ls *.txt > dir_*_all_txt.list
done
我想用子目录的名称替换
dir.*
。您可以在bash内操作字符串(请参见参数扩展
,或者只需在bash
手册页中搜索字符串##
),以删除最后一个斜杠之前的所有内容:
pax> for i in $HOME/tmp* ; do echo $i ${i##*/} ; done
/home/pax/tmp tmp
/home/pax/tmp1 tmp1
/home/pax/tmp2 tmp2
/home/pax/tmp3 tmp3
/home/pax/tmp4 tmp4
/home/pax/tmp5 tmp5
因此,在您的情况下,这将遵循以下原则:
for d in /home/* ;do
cd $d
ls *.txt > ${d##*/}_all_txt.list
done
尽管我应该提到,您的代码目前无法区分您正在检查的目录中的目录和文件,但您可能希望使用find-type d
仅查找目录,或者在循环中使用简单的检查它,如果[[-d${d}]]
:
for d in /home/* ; do
if [[ -d "${d}" ]] ; then
cd $d
ls *.txt > "${d##*/}_all_txt.list"
fi
done