Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash shell - Sort a list of words by the second letter?

I need to sort a list of words alphabetically by the second letter and I can't seem to figure out a way to do it.

Unsorted:

smokelessly
toelike
arsenous
malabar
antiperspirant
hock
nibbing
paleographically
goon

Sorted:

malabar
paleographically
nibbing
smokelessly
antiperspirant
hock
toelike
goon
arsenous

I've read about the sort command but it doesn't seem to have the functionality to let me do this?

like image 602
Vekta Avatar asked Dec 25 '22 09:12

Vekta


1 Answers

sort -kX.Y is your friend! X refers to the column and Y to the character.

$ sort -k1.2 file
malabar
paleographically
nibbing
smokelessly
antiperspirant
hock
toelike
goon
arsenous

If you want to define the last position to sort from, you can use

sort -k1.2,Z file

From man sort:

-k, --key=KEYDEF

sort via a key; KEYDEF gives location and type

KEYDEF is F[.C][OPTS][,F[.C][OPTS]] for start and stop position, where F is a field number and C a character position in the field; both are origin 1, and the stop position defaults to the line's end. If neither -t nor -b is in effect, characters in a field are counted from the beginning of the preceding whitespace. OPTS is one or more single-letter ordering options [bdfgiMhnRrV], which override global ordering options for that key. If no key is given, use the entire line as the key.

like image 103
fedorqui 'SO stop harming' Avatar answered Jan 09 '23 13:01

fedorqui 'SO stop harming'