Shell script to sort debian version numbers (line_

2019-04-14 23:11发布

问题:

I have a text file with entries representing build tags with version and build number in the same format as debian packages like this:

nimbox-apexer_1.0.0-12
nimbox-apexer_1.1.0-2
nimbox-apexer_1.1.0-1
nimbox-apexer_1.0.0-13 

Using a shell script I need to sort the above list by 'version-build' and get the last line, which in the above example is nimbox-apexer_1.1.0-2.

回答1:

Get the latest build with:

cat file.txt | sort -V | tail -n1

Now, to catch it into a variable:

BUILD=$(cat file.txt | sort -V | tail -n1)


回答2:

sort -n -t "_" -k2.3 file | tail -1


回答3:

cat file.txt | cut -d_ -f 2 | sed "s/-/./g" | sort -n -t . -k 1,2n -k 2,2n -k 3,3n  -k 4,3n

The 2n,3n are the number of characters considered relevant in that field. Increase them if you use really big version numbers...



回答4:

With GNU sort:

sort --version-sort file | tail -n -1

GNU tail doesn't like tail -1.



回答5:

I haven't been able to find a simple way to do this. I've been looking at code to sort ip address, which is similar to my problem, and trying to change my situation to that one. This what I have come up with. Please tell me there is a simpler better way !!!

sed 's/^[^0-9]*\([0-9]*\)\.\([0-9]*\)\.\([0-9]*\)-\([0-9]*\)/\1.\2.\3.\4 &/' list.txt | \
  sort -t . -n -k 1,1 -k 2,2 -k 3,3 -k 4,4 | \
  sed 's/^[^ ]* \(.*\)/\1/' | \
  tail -n 1

So starting with this data:

nimbox-apexer_11.9.0-2
nimbox-apexer_1.10.0-9
nimbox-apexer_1.9.0-1
nimbox-apexer_1.0.0-12
nimbox-apexer_1.1.0-2
nimbox-apexer_1.1.0-1
nimbox-apexer_1.0.0-13

The first sed converts my problem into a sorting IPs problem keeping the original line to reverse the change at the end:

11.9.0.2 nimbox-apexer_11.9.0-2
1.10.0.9 nimbox-apexer_1.10.0-9
1.9.0.1 nimbox-apexer_1.9.0-1
1.0.0.12 nimbox-apexer_1.0.0-12
1.1.0.2 nimbox-apexer_1.1.0-2
1.1.0.1 nimbox-apexer_1.1.0-1
1.0.0.13 nimbox-apexer_1.0.0-13 

The sort orders the line using the first four numbers which in my case represent mayor.minor.release.build

1.0.0.12 nimbox-apexer_1.0.0-12
1.0.0.13 nimbox-apexer_1.0.0-13 
1.1.0.1 nimbox-apexer_1.1.0-1
1.1.0.2 nimbox-apexer_1.1.0-2
1.9.0.1 nimbox-apexer_1.9.0-1
1.10.0.9 nimbox-apexer_1.10.0-9
11.9.0.2 nimbox-apexer_11.9.0-2

The last sed eliminates the data used to sort

nimbox-apexer_1.0.0-12
nimbox-apexer_1.0.0-13 
nimbox-apexer_1.1.0-1
nimbox-apexer_1.1.0-2
nimbox-apexer_1.9.0-1
nimbox-apexer_1.10.0-9
nimbox-apexer_11.9.0-2

Finally tail gets the last line which is the one I need.