Results of sort command are out of order.
This document (7001026) is provided subject to the disclaimer at the end of this document.
nl -ba < SourceTextFile.dat | sort -k 4,4 -k 1n | cut -f2- > SortedResults.txt
Here's a breakdown of this command:
nl -ba < SourceTextFile.dat
In this example the original source data file is "SourceTextFile.dat". "nl -ba" is run and the source data file is redirected as input for that command. The result is the same information with a line number at the beginning of each line. This line numbering will preserve the order for us in the sort command.
| sort -k 4,4 -k 1n
Next we use the pipe symbol "|" to send the new results to the sort command which says to sort the lines in the file based on the first key field "4,4" then as a secondary sort use the key field 1 and treat it as numerical (n). Field 4 is just an example and could be changed to any field you need to sort on. Field one is actually the field number you will need to use for sorting on the line numbers that have been added to each line.
Remember, since the line numbers have been added your data fields will now be incremented one to the right.
As a side note, "-k 4,4" is used to identify the beginning and ending point of the field to use for the primary sort. If the ending field was not specified then sort would assume the second "-k 1n" to be the ending value and attempt to sort on everything between 4 and 1.
| cut -f2- > SortedResults.txt
Finally, the line numbers will need to be removed from the entries and the results written to a file. The pipe symmbol "|" is used to send the now sorted information to the "cut" command. The "-f2-" says to display field 2 and all fields following to the end of the line, effectively removing the line numbers which are in field 1. That final output is redirected to the file "SortedResults.txt" which should be changed to whatever file name you would like to use.
This Support Knowledgebase provides a valuable tool for SUSE customers and parties interested in our products and solutions to acquire information, ideas and learn from one another. Materials are provided for informational, personal or non-commercial use within your organization and are presented "AS IS" WITHOUT WARRANTY OF ANY KIND.
- Document ID:7001026
- Creation Date: 24-Jul-2008
- Modified Date:03-Mar-2020
- SUSE Linux Enterprise Desktop
- SUSE Linux Enterprise Server
For questions or concerns with the SUSE Knowledgebase please contact: tidfeedback[at]suse.com