highestVersion() {
for TEST_PATH in `ls -a "$/TEMP"/*.flg`
do
echo " you are here"
TEST_FILE=`basename "$TEST_PATH"`
echo "$TEST_FILE"
done
}
下面是文件TEST_FILE
。在这种情况下,例如“RMG”是具有4个版本的书名。如何在这组文件中选择最新版本的文件并将其存储在变量中?我如何迭代这个,以便最后变量应该只包含具有最高版本号的唯一文件名?
ABC_EFG_FLOOL_DR3GCTEU_19951223_HANSHAKE_V03.flg
ABC_EFG_FLOOL_DR3GCTPC_19951223_HANSHAKE_V03.flg
ABC_RFTY_PICK_AMTY_19951223_HANSHAKE_V03.flg
ABC_JANE_PICK_AMTY_19951223_HANSHAKE_V02.flg
ABC_XYZ_RMG_19951223_HANSHAKE_V01.flg
ABC_XYZ_RMG_19951223_HANSHAKE_V02.flg
ABC_XYZ_RMG_19951223_HANSHAKE_V03.flg
ABC_XYZ_RMG_19951223_HANSHAKE_V11.flg
ABC_XYZ_ALG0_19951223_HANSHAKE_V02.flg
ABC_XYZ_SGFXMM_19951223_HANSHAKE_V03.flg
ABC_XYZ_STRIP_FULLREVAL_YU_1234_19951223_HANSHAKE_V02.flg
ABC_XYZ_STRIP_FULLREVAL_YU_1234_19951223_HANSHAKE_V03.flg
答案1
由于版本顺序与您的情况中的词汇顺序相同,因此使用 POSIX shell:
set -- ABC_XYZ_RMG_19951223_HANSHAKE_V*.flg
# now $1, $2... contain the files from the lowest version to highest.
shift "$(($# - 1))"
highest_version=$1
# or without shift:
eval "highest_version=\${$#}"
或者使用zsh
以下版本或最新版本bash
:
rmgs=(ABC_XYZ_RMG_19951223_HANSHAKE_V*.flg)
highest_version=${rmgs[-1]}
要对当前目录中的每个文件执行此操作(同样使用zsh
最新版本bash
(4.0 或更高版本)):
highest_versions() (
cd -P -- "$TEMP" || exit
typeset -A a
for f in *V??.flg; do
a[${f%V??.flg}]=$f
done
printf '%s\n' "${a[@]}"
)
在你的文件上,这给出了:
ABC_XYZ_STRIP_FULLREVAL_YU_1234_19951223_HANSHAKE_V03.flg
ABC_XYZ_RMG_19951223_HANSHAKE_V11.flg
ABC_JANE_PICK_AMTY_19951223_HANSHAKE_V02.flg
ABC_XYZ_ALG0_19951223_HANSHAKE_V02.flg
ABC_XYZ_SGFXMM_19951223_HANSHAKE_V03.flg
ABC_RFTY_PICK_AMTY_19951223_HANSHAKE_V03.flg
ABC_EFG_FLOOL_DR3GCTEU_19951223_HANSHAKE_V03.flg
ABC_EFG_FLOOL_DR3GCTPC_19951223_HANSHAKE_V03.flg
对于不支持关联数组的 shell,您可以通过调用类似以下操作的工具来执行相同操作awk
:
highest_versions() (
cd -P -- "$TEMP" || exit
awk 'BEGIN{
for (i = 1; i < ARGC; i++) {
key = val = ARGV[i]
sub(/V..\.flg/, "", key)
a[key] = val
}
for (i in a) print a[i]
exit}' *V??.flg
)
答案2
我喜欢perl
所以我会建议一个糟糕的解决方案:
#!/usr/bin/env perl
use strict;
use warnings;
my %highest_version_of;
for ( glob ( "*.flg" ) ) {
my ( $filename, $version ) = m/^(\w+)_V(\d+).flg/;
if ( $highest_version_of{$filename} //= 0 < $version ) { $highest_version_of{$filename} = $version };
}
foreach my $filename ( sort keys %highest_version_of ) {
print "${filename}_$highest_version_of{$filename}.flg\n";
}