Sriram P
Sriram P

Reputation: 309

How to sort alphanumeric by numbers in shell

Input file has data:

abc90
cd 18
bc14de
100def

Output should be:

bc14de
cd 18
abc90
100def

Is there any sort command to sort only by the number embedded in the alphanumeric data?

I tried this but it doesn't work as I want:

# sort -g FileName

Upvotes: 3

Views: 815

Answers (1)

anubhava
anubhava

Reputation: 785196

You can use:

awk -v OFS='\t' '{rec=$0; gsub(/[^[:digit:]]+/, "", rec); print rec, $0}' file
    | sort -nk1 | cut -d $'\t' -f2-
bc14de
cd 18
abc90
100def
  • awk is used to add a first column in input with only numeric characters using gsub
  • sort -nk1 is used for sorting input numerically on first column
  • cut is finally used to truncate first column

Upvotes: 4

Related Questions