So I am trying to sort a text file, call it tmp
, that contains 4 lines.
The first lines being:
table-name grade1 grade2 grade3
Richard 100 99 99
Fred 20 100 60
Alex 57 67 75
and have it sorted off based on the grades, if given, or default being their names. If they prompt for -n
and -r
it should also reverse and label numerically.
With $sort
being the field they want to sort.
What I've tried so far is variations of sort -k"$sort" -nr "$file"
but it only ever sorts off grade3
even if I ask it to sort grade1
.
With $sort
being the column number to have $file
sorted on, do this:
sort -nr -t' ' -k${sort},${sort} "${file}"
And here is a proof of concept for the 3 rows you posted:
$ cat testfile
Richard 100 99 99
Fred 20 100 60
Alex 57 67 75
$
$ sort -nr -t' ' -k3,3 testfile
Fred 20 100 60
Richard 100 99 99
Alex 57 67 75
$
$ sort -nr -t' ' -k4,4 testfile
Richard 100 99 99
Alex 57 67 75
Fred 20 100 60
$
I hope it helps.
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.