[英]awk and bash script
我有一個tgz文件,其中包含一個版本文件version.txt。 該文件只有一行“版本= 1.0.0”。 此tgz文件存在於兩個不同的目錄中,並且具有相同的名稱。
我的要求是,我需要使用bash腳本和awk來確定這兩個tgz文件中的哪個是最新版本。 即,具有1.0.0版本的tgz文件的版本低於具有1.0.1版本的文件的版本。
使用tar -xzvf /mnt/cf/bundle.tgz -O version.txt
提取版本。
棘手的部分是如何處理版本。 如果您的版本始終有三位數,那么我建議將每個部分乘以1000。這將為您提供一個很大的數字,您可以輕松地進行比較。 即1.0.0 == 1000000000; 1.0.1 =1000000001。另一種選擇是用%04d格式化每個部分:0001.0000.0000和0001.0000.0001。 這些字符串可以進行比較。
不好意思和負面評論表示歉意,但我總是對作業類型的問題感到懷疑。 為了彌補,我為您做到了。 您不需要awk,都可以用bash完成。
只需將F1和F2設置為正確的文件名即可。 我將其作為練習讓您接受它們作為命令行參數:)
#!/usr/bin/env bash
F1=f1.tgz
F2=f2.tgz
VERSION_FILE=version.txt
version1=`tar -xzf $F1 -O $VERSION_FILE|sed -e 's/.*version=//'`
version2=`tar -xzf $F2 -O $VERSION_FILE|sed -e 's/.*version=//'`
if [ "$version1" == "$version2" ]; then
echo "$F1 and $F2 contain the same version: $version1, $version2"
exit 0;
fi
( # start a subshell because we're changing IFS
# Assume F1 is the latest file unless we find otherwise below
latest_file=$F1
latest_version=$version1
# set the Internal Field Separator to a dot so we can
# split the version strings into arrays
IFS=.
# make arrays of the version strings
v1parts=( $version1 )
v2parts=( $version2 )
# loop over $v1parts, comparing to $v2parts
# NOTE: this assumes the version strings have the same
# number of components. If wont work for 1.1 and 1.1.1,
# You'd have to have 1.1.0 and 1.1.1
# You could always add extra '0' components to the shorter array, but
# life's too short...
for ((i = 0 ; i < ${#v1parts[@]} ; i++ )); do
# NOTE: ${#v1parts[@]} is the length of the v1parts array
if [ "${v1parts[i]}" -lt "${v2parts[i]}" ]; then
latest_file=$F2
latest_version=$version2
break;
fi
done
echo "$latest_file is newer, version $latest_version"
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.