Unix sort column without delimiter

I want to sort the contents of a file using a Unix script depending on a specific column:

ex: sort the following file in the third column:

ax5aa aa3ya fg7ds pp0dd aa1bb 

will look like

 pp0dd aa1bb aa3ya ax5aa fg7ds 

I tried sort -k 3.3, but just sort by 3d group of words (separator = SPACE).

Is there a way to sort unix as I like, or use another tool?

+6
source share
4 answers
 $ sort --key=1.3,1.3 inputfile pp0dd aa1bb aa3ya ax5aa fg7ds 

sorting help page:

[...]

-k, --key = POS1 [, POS2]

run the key in POS1 (start 1), end it on POS2 (default end of line)

[...]

POS - F [.C] [OPTS], where F is the number of the field, and C is the position of the character in the field; both are sources 1. If neither -t or -b are valid, the characters in the field are counted from the beginning of the previous space. OPTS is one or more one-letter order options that override the global order parameters for this key. If no key is specified, use the entire string as the key.

Using the --key = 1.3.1.3 key, you said that there is only one field (the entire line) and that you are comparing the position of the third character of this field.

+8
source

use sed to create columns before sorting

 $ echo "ax5aa aa3ya fg7ds pp0dd aa1bb" | sed 's/\(.\)/\1 /g' | sort -t ' ' -k3,3 | tr -d ' ' pp0dd aa1bb aa3ya ax5aa fg7ds 
+4
source
 cat inputfile | perl -npe 's/(.)/ $1/g' | sort -k 3,3 | perl -npe 's/ //g' 
+2
source

I would directly stick to perl and define a comparator

 echo $content | perl -e 'print sort {substr($a,3,1) cmp substr($b,3,1)} <>;' 
+1
source

Source: https://habr.com/ru/post/925201/


All Articles