如何在目录中获取特定文件名并将其保存在bash文件中

时间:2012-11-22 14:40:40

标签: bash directory

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

topout_B6_
topout__B6_
topout_B6_
topout_D2_
topout_D2_
topout_D2_

1 个答案:

答案 0 :(得分:1)

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

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

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

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

Find将返回文件的完整路径,因此您需要删除前导路径。一种方法是使用parameter substitution

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

最后,您可以将其写入文件。 (使用herestrings

>outfile <<<$stripped_files