首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >用于查找最新文件匹配模式的Bash函数

用于查找最新文件匹配模式的Bash函数
EN

Stack Overflow用户
提问于 2011-05-04 23:31:16
回答 5查看 138.8K关注 0票数 161

在Bash中,我想创建一个函数来返回与特定模式匹配的最新文件的文件名。例如,我有一个包含如下文件的目录:

代码语言:javascript
复制
Directory/
   a1.1_5_1
   a1.2_1_4
   b2.1_0
   b2.2_3_4
   b2.3_2_0

我想要以'b2‘开头的最新文件。我如何在bash中做到这一点?我需要将它放在我的~/.bash_profile脚本中。

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2011-05-04 23:35:50

ls命令有一个按时间排序的参数-t。然后你可以用head -1抓取第一个(最新的)。

代码语言:javascript
复制
ls -t b2* | head -1

但请注意:Why you shouldn't parse the output of ls

我个人的观点:只有当文件名包含有趣的字符,如空格或换行符时,解析ls才是危险的。如果您可以保证文件名不会包含有趣的字符,那么解析ls是非常安全的。

如果您正在开发一个脚本,该脚本将在许多不同的情况下由许多人在多个系统上运行,那么我强烈建议您不要解析ls

下面是如何“正确”做这件事:How can I find the latest (newest, earliest, oldest) file in a directory?

代码语言:javascript
复制
unset -v latest
for file in "$dir"/*; do
  [[ $file -nt $latest ]] && latest=$file
done
票数 264
EN

Stack Overflow用户

发布于 2014-11-06 04:46:57

这是所需Bash函数的可能实现:

代码语言:javascript
复制
# Print the newest file, if any, matching the given pattern
# Example usage:
#   newest_matching_file 'b2*'
# WARNING: Files whose names begin with a dot will not be checked
function newest_matching_file
{
    # Use ${1-} instead of $1 in case 'nounset' is set
    local -r glob_pattern=${1-}

    if (( $# != 1 )) ; then
        echo 'usage: newest_matching_file GLOB_PATTERN' >&2
        return 1
    fi

    # To avoid printing garbage if no files match the pattern, set
    # 'nullglob' if necessary
    local -i need_to_unset_nullglob=0
    if [[ ":$BASHOPTS:" != *:nullglob:* ]] ; then
        shopt -s nullglob
        need_to_unset_nullglob=1
    fi

    newest_file=
    for file in $glob_pattern ; do
        [[ -z $newest_file || $file -nt $newest_file ]] \
            && newest_file=$file
    done

    # To avoid unexpected behaviour elsewhere, unset nullglob if it was
    # set by this function
    (( need_to_unset_nullglob )) && shopt -u nullglob

    # Use printf instead of echo in case the file name begins with '-'
    [[ -n $newest_file ]] && printf '%s\n' "$newest_file"

    return 0
}

它只使用Bash内置,并且应该处理名称中包含换行符或其他不常见字符的文件。

票数 8
EN

Stack Overflow用户

发布于 2011-05-05 00:11:58

不常见的文件名(例如包含有效\n字符的文件)可能会对这种解析造成严重影响。下面是在Perl中实现这一点的方法:

代码语言:javascript
复制
perl -le '@sorted = map {$_->[0]} 
                    sort {$a->[1] <=> $b->[1]} 
                    map {[$_, -M $_]} 
                    @ARGV;
          print $sorted[0]
' b2*

这是那里使用的Schwartzian transform

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5885934

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档