IF取决于每个文件夹的文件数--unix

时间:2013-04-22 18:52:50

标签: file unix if-statement count ls

我想根据每个文件夹中以相同的两个字母开头的文件数做不同的操作---如果TS中的文件小于或等于6则执行一组操作,否则执行另一组操作 我的数据看起来像这样

files/TS01 -- which has 2 files  
files/TS02 -- which has 5 files 
files/TS03 -- which has 2 files 
files/TS04 -- which has 7 files
files/TS05 -- which has 9 files

我试过了

FILES="$TS*"
for W in $FILES
do
    doc=$(basename $W) 
    if [ $W -le 6 ] 
    then
    ....
    done ...
    fi
done

但是我收到错误“预期整数表达式”

我试过

if [ ls $W -le 6 ] 

我得到另一个错误说“太多论点”

你能帮忙吗

1 个答案:

答案 0 :(得分:2)

为了得到我想把管道ls -l推荐给wc -l的行数,这会吐出目录中的行数,如下所示......

Atlas $ ls -l | wc -l
    19

我制作了一个小脚本,展示了如何使用这个结果有条件地做一件事......

#!/bin/bash

amount=$(ls -l | wc -l)

if [ $amount -le 5 ]; then
    echo -n "There aren't that many files, only "
else
    echo -n "There are a lot of files, "
fi

echo $amount

在包含19个文件的文件夹上执行时,它会回显..

Atlas $ ./howManyFiles.sh
    There are a lot of files, 19

以及少于5个文件的那个......

Atlas $ ./howManyFiles.sh
    There aren't that many files, only 3

希望这有助于向您展示如何从文件夹中获取可用的文件数,然后如何在“if”语句中使用这些结果!