William LAM
William LAM

Reputation: 455

Custom sorting in shell

I would like to have custom order for a sorting: 'D','R' -> 'I' -> 'W','X' and 'Z'. That is, 'D' and 'R' are equal and sort before 'I'; and 'W', 'X' and 'Z' are equal and sort after 'I'.

Input:

123D123
234R111
333I333
111W111
222X222
111Z111

The sorting will be on the 4th character, and then followed by a sorting from 5th to 7th characters.

The expected output would be:

234R111
123D123
333I333
111W111
111Z111
222X222

Upvotes: 1

Views: 107

Answers (1)

karakfa
karakfa

Reputation: 67567

paste <(cut -c 4-7 file | tr 'RWX' 'DZZ') <(cat file) | sort -k 1,1 | awk '{print $2}'

234R111
123D123
333I333
111W111
111Z111
222X222

Explanation: create a key where R=D and W=X=Z, sort by key, discard the key

Upvotes: 1

Related Questions