简体   繁体   中英

Linux sort folders by numerical value

We have a data set from

ls -1 /opt/test/kortinfo/
1.0.0
1.0.1
1.0.2
1.1.0
1.10.0            // Error
1.2.0
1.3.0
1.4.0
1.5.0
1.5.1
1.5.2
1.6.0
1.7.0
1.8.0
1.8.1
1.9.0

As we can see here the folder 1.10.0 is misplaced since it is larger than 1.9.0

We tried to pipe it through sort -g , sort -n and sort -ng but neither will correctly display the folders sorted by their number values.

ls -1 /opt/test/kortinfo/ | grep -v "siste" | sort -ng
1.0.0
1.0.1
1.0.2
1.1.0
1.10.0            // Still the same error
1.2.0
1.3.0
1.4.0
1.5.0
1.5.1
1.5.2
1.6.0
1.7.0
1.8.0
1.8.1
1.9.0

Does anyone know how I can get these sorted correctly by number value?

Use the -v switch of ls :

ls -v

man ls says:

-v natural sort of (version) numbers within text

As a reference, one could also solve this problem with padding the version numbers with brace expansion, if applicable.

Here's an example

touch 1.{01..10}.{01..05}

This will create the versions with appropriate padding of the version representations and simplify your life significantly.

The result:

mace-windu:useme [ ~/Desktop/1 ] ls -1
1.01.01
1.01.02
1.01.03
1.01.04
1.01.05
1.02.01
1.02.02
1.02.03
1.02.04
1.02.05
1.03.01
1.03.02
1.03.03
1.03.04
1.03.05
1.04.01
1.04.02
1.04.03
1.04.04
1.04.05
1.05.01
1.05.02
1.05.03
1.05.04
1.05.05
1.06.01
1.06.02
1.06.03
1.06.04
1.06.05
1.07.01
1.07.02
1.07.03
1.07.04
1.07.05
1.08.01
1.08.02
1.08.03
1.08.04
1.08.05
1.09.01
1.09.02
1.09.03
1.09.04
1.09.05
1.10.01
1.10.02
1.10.03
1.10.04
1.10.05

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM