In this HackerRank Sort Command #5 problem solution, You are given a file of text,which contains temperature information about American cities, in TSV (tab-separated) format. The first column is the name of the city and the next four columns are the average temperature in the months of Jan, Feb, March and April (see the sample input). Rearrange the rows of the table in descending order of the values for the average temperature in January.

Input Format

A text file where each line contains a row of data as described above.

Output Format

Rearrange the rows of the table in descending order of the values for the average temperature in January (i.e, the mean temperature value provided in the second column).

The 'Sort' Command Line Program

This is frequently used for sorting input in text or TSV formats, in various different ways supported by it; which may be either lexicographical, case insensitive, based on the numeric field only, based on a particular column, etc. Using a variety of flags and options, sort can also be extended in various powerful ways. The command can also be used for sorting tables of data, delimited by commas (csv) or tabs (tsv) or even spaces; on a particular column or field. The -k option helps sort the input file on a particular field, i.e. the column number.

HackerRank Sort Command #5 problem solution


Problem solution.

sort -t $'\t' -k2 -n -r


Second solution.

#!/usr/bin/env bash
cat |sort -t$'\t' -n -r -k2


Third solution.

sed 's/\t/|/g' | sort -t '|' -k 2 -n -r | sed 's/|/\t/g'


Fourth solution.

sort -nr -k 2 -t $'\t'