From d3e6a853a37d6f5c42b46fd6671f9308c3265838 Mon Sep 17 00:00:00 2001 From: Michele Cereda Date: Thu, 5 May 2022 23:51:04 +0200 Subject: [PATCH] Added example with explanation to sort's notes --- knowledge base/sort.md | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/knowledge base/sort.md b/knowledge base/sort.md index 183fa44..cdc3cde 100644 --- a/knowledge base/sort.md +++ b/knowledge base/sort.md @@ -14,4 +14,36 @@ sort -n path/to/file # Sort lines and remove duplicates. sort -u path/to/file + +# Sort by the value in the last field. +awk 'BEGIN {FS=","; OFS="|"} {print $NF,$0}' file.txt \ + | sort -n -t '|' | awk -F '|' '{print $NF}' ``` + +## Sort by the value in the last field + +1. copy the last field (column) of each line at the beginning of each of the lines with a different delimiter: + + ```shell + awk 'BEGIN {FS=","; OFS="|"} {print $NF,$0}' file.txt + ``` + +1. sort on the 1st field specifing the delimiter to be the character above: + + ```shell + awk 'BEGIN {FS=","; OFS="|"} {print $NF,$0}' file.txt | sort -n -t '|' + ``` + +1. discard the first field + + ```shell + awk 'BEGIN {FS=","; OFS="|"} {print $NF,$0}' file.txt | sort -n -t '|' | awk -F '|' '{print $NF}' + awk 'BEGIN {FS=","; OFS="|"} {print $NF,$0}' file.txt | sort -n -t '|' | awk -F '|' '{print $2}' + awk 'BEGIN {FS=","; OFS="|"} {print $NF,$0}' file.txt | sort -n -t '|' | cut -d '|' -f 2 + ``` + +## Sources + +- [Sort a file in Unix based on the last field] + +[sort a file in unix based on the last field]: http://www.unixcl.com/2010/11/sort-file-based-on-last-field-unix.html