Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash - Awk sort -n not sorting

Tags:

linux

bash

awk '{for(i=1; i<=NF; i++) printf("%d ",$i)}' | sort -n

it reads a file like

55 89 33 20

and prints it out normally, not numerically sorted. Why?

like image 996
Tree55Topz Avatar asked Dec 28 '25 10:12

Tree55Topz


1 Answers

sort works on a per-line basis, and printf doesn't append a newline by default, you need to specify it. So use:

awk '{for(i=1; i<=NF; i++) printf("%d\n",$i)}' | sort -n

This will print out your numbers on separate lines, if you want them to be in a single line again then you can pipe it to paste:

awk '{for(i=1; i<=NF; i++) printf("%d\n",$i)}' | sort -n | paste -s -d ' '

You can also just use print instead of printf, this will append the newline by default:

awk '{for(i=1; i<=NF; i++) print $i}' | sort -n
like image 108
Josh Jolly Avatar answered Dec 30 '25 23:12

Josh Jolly