Tuesday 17 April 2018

How to sort lines in Linux, starting with a specific character position, using "sort"

Let's say we have an file with a list of DB names:

$cat my_file.txt
BMLCRM12
BMLCRM98
BMLCRM99
BMSCRM11
BMSCRM13
BMSCRM15
BMSCRM19
BMSCRM23
BMSCRM24
BMSCRM25

The goal is to sort them out in order, ignoring the first 6 characters.

Solution:

$cat my_file.txt |sort -n -k 1.6,1.8

BMSCRM11
BMLCRM12
BMSCRM13
BMSCRM15
BMSCRM19
BMSCRM23
BMSCRM24
BMSCRM25
BMLCRM98
BMLCRM99