在Bash中,我想创建一个函数来返回与特定模式匹配的最新文件的文件名。例如,我有一个包含如下文件的目录:
Directory/
a1.1_5_1
a1.2_1_4
b2.1_0
b2.2_3_4
b2.3_2_0
我想要以'b2‘开头的最新文件。我如何在bash中做到这一点?我需要将它放在我的~/.bash_profile
脚本中。
发布于 2011-05-04 23:35:50
ls
命令有一个按时间排序的参数-t
。然后你可以用head -1
抓取第一个(最新的)。
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?
unset -v latest
for file in "$dir"/*; do
[[ $file -nt $latest ]] && latest=$file
done
发布于 2014-11-06 04:46:57
这是所需Bash函数的可能实现:
# 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内置,并且应该处理名称中包含换行符或其他不常见字符的文件。
发布于 2011-05-05 00:11:58
不常见的文件名(例如包含有效\n
字符的文件)可能会对这种解析造成严重影响。下面是在Perl中实现这一点的方法:
perl -le '@sorted = map {$_->[0]}
sort {$a->[1] <=> $b->[1]}
map {[$_, -M $_]}
@ARGV;
print $sorted[0]
' b2*
这是那里使用的Schwartzian transform。
https://stackoverflow.com/questions/5885934
复制相似问题