11

Considering the following input file (example)...

afaefkl    aaa
al kmm     ddd
aajwoe     bbb
bnm aefp   ccc

... what would be the most straight-forward way to sort it by column 2 (starting at character position 12 in each line) using standard Unix/Linux tools only?

Note that the whitespace consists of spaces only, there are no tabs, so sort -k2 fails for obvious reasons.

The expected output would be as follows:

afaefkl    aaa
aajwoe     bbb
bnm aefp   ccc
al kmm     ddd
3
  • The answer from manatwork answers this question, to some extend. I see how this question can stand on it's own, but I like watching the unix.SE crowd closing questions left and right. Please forgive my cynicism.
    – Lesmana
    Commented Nov 25, 2015 at 23:36
  • 3
    @lesmana: I don't understand — you're cynical about the unix.SE crowd closing questions left and right, so you vote to close a question as a duplicate of a question that's only vaguely related, just to see whether you can trick four other people into seeing the emperor's clothes?  manatwork's answer doesn't answer this question.  True, somebody who sees the answer to this question might look at manatwork's answer and say, "Oh, yes, that makes sense now," but it's not an answer to this question. Commented Nov 25, 2015 at 23:57
  • 2
    Objecting to the duplicate tag, these are clear separate problems, the solution to the linked one is not a solution to this one. I would even contest the position that the linked answer answers this question to any extent, beyond the regugitated man-page text containing the detail, but it's not called out, as this problem isn't the problem that answer answers.
    – Phil
    Commented Aug 10, 2022 at 1:12

1 Answer 1

17

man sort suggests that you can use sort --key=1.12 to get the desired effect.

1
  • Now I'm kind of surprised that this actually works. I came up with the following solution: sort -t @ -k1.12 file.txt I thought I had to trick sort into ignoring the spaces by using the @ sign (that doesn't appear anywhere in the file) as a placeholder. However, as your answer suggests, sort automagically assumes that I want to sort by text starting at a certain character position and disregards the spaces if you call something like sort -k1.12 ... :)
    – tmh
    Commented Nov 25, 2015 at 20:02

Not the answer you're looking for? Browse other questions tagged .