user2509229
user2509229

Reputation: 43

sorted by the string position in each word UNIX

I have a list of dictionary words and i need to create a command that will sort the words by the string position of a particular word in UNIX
for e.g. i have following lines

chemistry
mistery
alchemist
warmish

If i created a command say findsort and execute it as
findsort mis
my output should be

mistery
chemistry
warmish
alchemist

Upvotes: 1

Views: 98

Answers (1)

twalberg
twalberg

Reputation: 62379

Using just standard shell utilities, you could do this:

awk -v search="mis" '{ print index($0, search), $0 }' input.txt | sort -k1,1n -k2,2 | cut -d' ' -f2-

This might possibly mess with spaces in your lines a bit if your input is more general (i.e. not single-word lines), but given the example you did, this shouldn't be an issue. If it is, you will need to play around a bit with a custom delimiter.

It wouldn't be too hard to write some Python or Perl code to accomplish the same thing.

Upvotes: 1

Related Questions