bash脚本列出目录中的文件

时间:2015-01-13 11:10:06

标签: linux bash

我正在编写一个带有参数的脚本,该参数是一个目录 我希望能够构建包含该目录中具有特定扩展名的所有文件的列表/数组并切断其扩展名。 例如,如果我的目录包含:

  • aaa.xx
  • bbb.yy
  • ccc.xx

即时搜索* .xx。
我的列表/数组将是:aaa ccc。
我尝试使用此线程中的代码example接受的答案。

set tests_list=[]

for f in $1/*.bpt
do
   echo $f
   if [[ ! -f "$f" ]]
   then
      continue
   fi
   set tmp=echo $f | cut -d"." -f1
   #echo $tmp
   tests_list+=$tmp                                                         
done

echo ${tests_list[@]}

如果我运行这个脚本,我得到的循环只执行一次,$ f是tests_list = [] / * .bpt这很奇怪,因为$ f应该是该目录中的文件名,并且回显空字符串。 /> 我验证了我在正确的目录中,并且参数目录中的文件扩展名为.bpt。

2 个答案:

答案 0 :(得分:2)

这应该适合你:

for file in *.xx ; do echo "${file%.*}" ; done

将此扩展为将参数作为目录的脚本:

#!/bin/bash

dir="$1"
ext='xx'

for file in "$dir"/*."$ext"
do
    echo "${file%.*}"
done

编辑:用ls切换for - 感谢@tripleee进行更正。

答案 1 :(得分:1)

filear=($(find path/ -name "*\.xx"))
filears=()
for f in ${filear[@]}; do filears[${#filears[@]}]=${f%\.*}; done 
相关问题