0

我正在编写一个脚本来读取文件夹并将文件名与变量进行比较。

文件名和变量都将时间作为字符串作为它们的值。

Ed:文件名 - 131222 变量 = 133000

我的文件夹包含具有相似命名约定的文件列表,按时间顺序递增。我的变量将介于两个文件名中的任何一个之间。我需要确定最有可能接近(较小)变量的文件。

我正在使用 bash shell 脚本。

我该怎么做这个比较?我正在使用 for 循环迭代读取文件夹中的文件名。但我对如何进行比较一无所知。

4

3 回答 3

0

如果您确定目录中的所有文件的文件名中都只有数字,那么这将起作用:

need=200 # we're looking for a file that is closest to 200
ls -1 | sort -n | awk "{if(\$1 > $need && prev != \"\") {print ($need-prev < \$1-$need) ? prev : \$1; x=1; exit} prev=\$1} END{if (x != 1) print prev}"


但我强烈推荐这个(因为它有一个额外的文件名检查!):

#!/bin/bash

need=500

shopt -s nullglob # just in case there are no files at all

for curFile in *; do
    if ! [[ $curFile =~ ^[0-9]+$ ]]; then # if there are files that have other symbols besides numbers
        echo "Wrong filename format: $curFile"
        continue
    fi

    (( curFile <= need )) && ( ((need - curFile < need - smaller )) || [[ -z $smaller ]] ) && smaller=$curFile
    (( curFile >= need )) && ( ((curFile - need < higher - need )) || [[ -z $higher ]] ) && higher=$curFile
done

if [[ -n $smaller ]] && (( need - smaller < higher - need )) || [[ -z $higher ]]; then
    echo "$smaller"
else
    echo "${higher}"
fi

如果您有两个距离相似的文件(例如1020并且您正在搜索15),它将输出更高的数字。

于 2013-09-08T17:41:00.593 回答
0

尝试使用expr...

filename="123"
ToCompare=100
cmp=`expr $filename - $ToCompare`
if [ $cmp -lt 0 ] ; then
    #file has lower value
else
    #file has higher value

fi 
于 2013-09-08T16:46:03.443 回答
0

如果我明白...

使用两个for循环,在第一个确定较近的文件。在第二个中for选择“接近度”等于第一个中确定的更接近的文件的文件for

min=1000000000
var=131119

for file in $(ls -1)
do
    if [ $var -le $file ]
    then
        diff=$(($file - $var))
        if [ $diff -lt $min ]; then min=$diff; fi
        echo "$file - $var = $(($file - $var))"
    fi
done

echo $min

for file in $(ls -1)
do
    if [ $var -le $file ]
    then
        diff=$(($file - $var))
        if [ $min -eq $diff ]
        then
            echo "This is your file: $file"
        fi
    fi
done

不过很多代码。

于 2013-09-08T18:10:26.303 回答