【问题标题】:Comparing the filenames with an integer and reading the filename that is less than the integer将文件名与整数进行比较并读取小于整数的文件名
【发布时间】:2013-09-08 16:40:47
【问题描述】:

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

文件名和变量的值都是字符串。

Ed:文件名 - 131222 变量 = 133000

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

我正在使用 bash shell 脚本。

我该如何进行比较?我正在使用 for 循环迭代读取文件夹中的文件名。但我不知道如何进行比较。

【问题讨论】:

    标签: bash unix


    【解决方案1】:

    尝试使用expr ...

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

    【讨论】:

    • else # file has higher *or equal* value。 @user2759260 您确定目标编号永远不会等于文件名吗?如果可能,请使用-le 而不是-lt
    【解决方案2】:

    如果我明白...

    使用两个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
    

    虽然有很多代码。

    【讨论】:

      【解决方案3】:

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

      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),它将输出更大的数字。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-11-23
        • 2014-10-10
        • 2020-07-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多