1

What I want to achieve is sorting lines of text by a specific point in the text (the lines of text have no spaces or columns). I've worked out a solution to this, but I want to know if there is a more direct and simple way of doing it.

My current method for this is to cause a break i.e. make a new column at the same place on every line (just before the point I want to sort by - this being Sn_L001_Rn) and then sort by that column, and then join the two columns back together. this works but it seems overly complicated and clunky. I've seen posts on making a score system with awk, but as mine are going to go to at least 96, then this seems lengthy. also i've seen sqlite might be applicable, but this also seems equally lengthy. I apologise if this question has already been asked, but so far I have failed to find a simple method to resolve it.

Here is some example input:

SOON_S2_L001_R1_001.txt    
SOON_S2_L001_R2_001.txt    
HELLO_S4_L001_R1_001.txt    
HELLO_S4_L001_R2_001.txt    
BASH_S1_L001_R1_001.txt    
BASH_S1_L001_R2_001.txt    
WORLD_S3_L001_R1_001.txt    
WORLD_S3_L001_R2_001.txt    

Desired output:

BASH_S1_L001_R1_001.txt    
BASH_S1_L001_R2_001.txt    
SOON_S2_L001_R1_001.txt    
SOON_S2_L001_R2_001.txt    
WORLD_S3_L001_R1_001.txt    
WORLD_S3_L001_R2_001.txt    
HELLO_S4_L001_R1_001.txt    
HELLO_S4_L001_R2_001.txt    

To add further complexity, in a situation where the is more than 1 of the same Sn then I would like it to take into account the name (though I think this may be resolvable using flags in sort).

  • ahh i looked through the man page and didn't put 2 and 2 together. right so i use the -t flag to tell sort that _ classifies a new column. then the -k2 verifies which column to sort by and the ,2 means sort from beginning to end of column 2. well thats certainly simpler than making columns prior to using sort. cheers man, your crazy quick at this, and also i keep making an idiot of myself with my faulish questions. I will try and reduce my idiocy with time – Giles May 23 '16 at 14:46
  • If the answer below solves your problem, don't forget to use the checkmark to indicate that to the system. Otherwise, please leave a comment to clarify. Thank you! – Jeff Schaller May 27 '16 at 15:27
1

sort -t_ -k2 infile will sort data using the 2nd key with underscore as separator.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.