0

我需要将包含一些特殊术语(如“B_”和“D_”)的目录中的目录名称保存到文本文件中,但只有文件名而不是整个目录,但我不知道如何在 bash 中执行此操作。我需要一个如下所示的文本文件作为输出:

topout_B6_
topout__B6_
topout_B6_
topout_D2_
topout_D2_
topout_D2_
4

1 回答 1

1

如果您的文件名足够简单,您可以使用 glob 扩展来获取它们的列表。此全局扩展将不包括任何父目录(但可能包括子目录)。

files=(*B_* *D_*) #stores an array of file names in $files

如果模式更复杂并且您需要正则表达式,则可以使用find实用程序。

files=($(find . -type f -regex ".*[BD]_?.*))

Find 将返回文件的完整路径,因此您需要去除前导路径。一种方法是使用参数替换

stripped_files=$(for f in "${files[@]}"; do echo ${f##*/}; done) #iterate over array values

最后,您可以将其写入文件。(使用这里字符串

>outfile <<<$stripped_files
于 2012-11-22T15:56:32.183 回答