Mint.K
Mint.K

Reputation: 899

sort command using multiple delimiters in bash

sort -k 2 data.txt

Using the -k option, we can specify which fields to compare. However, fields are separated by white space. How do I modify my commands so I can make my delimiters white space and the colon ':' together?

For example,

james:ben tom:jamie

has 4 fields.

Expected input: my data.txt file:

apple:tiger jack
orange:ant tom
pear:bird james

Expected output: using sort command with -k 2

orange:ant tom
pear:bird james
apple:tiger jack

Upvotes: 1

Views: 1766

Answers (1)

Alfe
Alfe

Reputation: 59426

I'd be interested if you find a proper solution. My current workaround for situations like these is modifying the input for sort and undo the modification afterwards:

printf "1:2 3:4\n2:3 4:1\n3:4 1:2\n4:1 2:3\n" |
  sed 's/:/ :/g' | sort -k 4 | sed 's/ :/:/g'

You can modify the number after -k to any number from 1 through 4. Output will be sth like this (for 4):

2:3 4:1
3:4 1:2
4:1 2:3
1:2 3:4

Upvotes: 2

Related Questions