【问题标题】:how to put a filename from the newest file in the directory into a variable如何将目录中最新文件中的文件名放入变量中
【发布时间】:2012-10-09 19:13:16
【问题描述】:

我正在编写脚本。我需要自动化查看目录中包含名称中包含字符串“HNAZXLCOM”的所有文件的部分,然后获取名称中包含该字符串的最新文件并将文件名放入变量中。

谢谢

【问题讨论】:

    标签: bash shell variables ls


    【解决方案1】:
    function latest {
        if [[ $FUNCNAME == ${FUNCNAME[1]} ]]; then
            unset -v x latest files
            printf -v "$@"
        elif (($# > 2)); then
            printf '%s\n' "Usage: $FUNCNAME <glob> <varname>" 'Error: Takes at most 2 arguments. Glob defaults to *'
            return 1
        else
            if ! shopt -q nullglob; then
                typeset -f +t "$FUNCNAME"
                trap 'shopt -u nullglob; trap - RETURN' RETURN
                shopt -s nullglob
            fi
    
            IFS= typeset -a 'files=(${1:-*})'
            typeset latest x
    
            for x in "${files[@]}"; do
                [[ -d $x || $x -ot $latest ]] || latest=$x
            done
    
            ${2:+"$FUNCNAME"} "${2:-printf}" -- %s "$latest"
        fi
    }
    
    
    latest '*HNAZXLCOM*' myVar
    

    【讨论】:

      【解决方案2】:

      如果我没看错

      var="$(ls -t1 *HNAZXLCOM*|head -n 1)"
      

      【讨论】:

      • 还是包含字符串、文件或文件名的目录?
      【解决方案3】:

      在 man ls 中,-t 开关是相关的。另请参阅 -1 开关。

      -t     sort by modification time, newest first  
      -1     list one file per line
      

      -1 开关不相关,因为ls 在输出到管道时自动为每个名称写入一行。

      在命令提示符下,以下函数将列出 13 个最近的文件;例如,xt *HNAZXLCOM* 将列出名称中包含该字符串的 13 个最新文件,而 xt 本身将列出当前工作目录中的最新文件(任何模式)。将数字调整为您喜欢的任何值。某些版本的 head 可能需要 -n 13 而不是 -13。在您的应用程序中,
      H=$(ls -t *HNAZXLCOM* | head -n 1)
      合适。

      xt () 
      { 
          date;
          ls --color -Glt --color --time-style="+%Y-%m-%d %T" $* | grep -v "/" | head -13
      }
      

      【讨论】:

        猜你喜欢
        • 2020-12-28
        • 1970-01-01
        • 2021-12-11
        • 1970-01-01
        • 1970-01-01
        • 2015-03-22
        • 2020-07-28
        • 2017-07-07
        • 1970-01-01
        相关资源
        最近更新 更多