Shell script to sort debian version numbers (line_

2019-04-14 22:43发布

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.

5条回答
乱世女痞
2楼-- · 2019-04-14 23:08

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)
查看更多
姐就是有狂的资本
3楼-- · 2019-04-14 23:16

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.

查看更多
不美不萌又怎样
4楼-- · 2019-04-14 23:19

With GNU sort:

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

GNU tail doesn't like tail -1.

查看更多
爱情/是我丢掉的垃圾
5楼-- · 2019-04-14 23:23
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...

查看更多
SAY GOODBYE
6楼-- · 2019-04-14 23:28
sort -n -t "_" -k2.3 file | tail -1
查看更多
登录 后发表回答