如何列出根文件夹的每个子目录中的一个文件?

如何列出根文件夹的每个子目录中的一个文件?

如果这很简单,请原谅 - 但是如何在我的根文件夹的每个子目录中仅列出一个文件?Linux 终端或 MS DOS 语法无关紧要。我猜它会是一个带有某些参数的 ls 或 dir 命令,但我在手册中没有找到这两个命令的任何内容。

答案1

如果你想查看目录名称使用 -

ls -R1 | grep -A 1 “:”

如果你不想看到目录名称,请使用 -

ls -R1 | grep -A 1 ":" | grep -v“:”

答案2

以下命令执行:

for d in `find / -maxdepth 1 -mindepth 1 -type d`; do find $d -maxdepth 1 -type f | head -n1 ;done

答案3

写了一个小脚本来完成这个任务。

#!/bin/bash
for dir in `find . -type d` # Find directories recursively
do
  # cd into directory, quotes are for directory names with spaces
  cd "$dir"             

  # Print out directory name
  echo "In directory $dir:"

  # Force list output to be one entry per line, pipe through inverted grep to 
  # exclude directories, pipe through awk to get the first item. You can specify
  # the number of files you want.     
  ls -p1 | grep -v / | awk -v "num_of_files=1" 'NR<=num_of_files { print $1 }'

  # cd back to root directory
  cd "$OLDPWD"              
done

输出:

In directory .:
test.sh
In directory ./bar:
barfile.txt
In directory ./baz:
bazfile.txt
In directory ./baz/quux:
something.txt
In directory ./foo:
foofile.txt

答案4

find -type d -print0 | xargs -0 ls | awk '/^\.\//||newdir{newdir=!newdir;print}'
  • find -type d将所有子目录获取到当前目录。
  • -print0-0处理有问题的文件名(空格、换行符等)。
  • awk如果行开头匹配./(表示目录)或变量newdir为,则神秘命令将继续true。如果继续,newdir将设置为其相反值(即true,如果为false,反之亦然)并打印该行。

部分内容详细说明awk:遇到目录时,newdir默认情况下false(因为未设置)将设置为,true并打印目录。在下一行,^\.\/将不匹配,但newdir现在将是true,并且将再次运行括号。现在newdir将设置为其相反项(false),并打印行。现在,直到出现下一个目录,才会打印任何行。

awk在此示例中,嵌入换行符的文件名将无法得到正常处理。

相关内容