Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
335 views
in Technique[技术] by (71.8m points)

shell - How to sort a text list of files by sizes such as as 1.0M, 2.0G and 3.5K?

Here is the content of the text file:

I tried several ways but couldn't find a solution. One of them was:

cat filelist.txt | sort -nk0

Here is text result : 1.3M /usr/perl5/5.8.4/lib/i86pc-solaris-64int/auto/Encode/JP/JP.so

1.2M /usr/perl5/5.8.4/lib/i86pc-solaris-64int/auto/Encode/KR/KR.so

1.1M /usr/perl5/5.8.4/lib/i86pc-solaris-64int/auto/Encode/CN/CN.so

1.0M /usr/perl5/5.8.4/lib/i86pc-solaris-64int/auto/Encode/TW/TW.so

190K /usr/perl5/5.8.4/lib/i86pc-solaris-64int/auto/Encode/Byte/Byte.so

138K /usr/perl5/5.8.4/lib/i86pc-solaris-64int/auto/re/re.so

113K /usr/perl5/vendor_perl/5.8.4/i86pc-solaris-64int/auto/DBD/Pg/Pg.so

106K /usr/perl5/5.8.4/lib/i86pc-solaris-64int/auto/B/B.so

106K /usr/perl5/5.6.1/lib/i86pc-solaris-64int/auto/re/re.so

104K /usr/perl5/5.8.4/lib/i86pc-solaris-64int/auto/POSIX/POSIX.so

14.1K /usr/perl5/vendor_perl/5.8.4/i86pc-solaris-64int/auto/DBI/DBI.so


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use awk to convert the sizes to bytes and then sort with -n:

awk '$1 ~ /M/ { $1=$1*1000000 } $1 ~ /K/ { $1=$1*1000 } $1 ~ /G/ { $1=$1*1000000000 }1' filelist.txt | sort -n 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...