0

I have a file trial.txt in which I want to sort its fourth column only without changing the order of the other colums . My file contents is like this.

A user 9 12 ab    
B user 2 9 cd    
C user 5 13 da

I want my output to look like this

A user 9 13 ab    
B user 2  12 cd    
C user 5  9 da

I had tried this.

sort -k 4 trial.txt

but it is not giving the output as expected.

Inian
  • 80,270
  • 14
  • 142
  • 161

2 Answers2

0

use:
sort -k4 -n -s trial.txt
Apart from the k option, it is advised you use -n for comparing numbers, the -s option suppresses the last resort comparison. check the manual for more info. Also, your required output is showing descending order, in case use -r option to reverse the sorting pattern.

Akash
  • 939
  • 1
  • 8
  • 27
  • Thank you for your suggestion, but yet this is still not working. As ,I am using -n for comparing the numbers, but also not working and still giving the same output as above. I want to do it with sed or with awk. As ,alone sort cannot do this. please have a look on this using some sed and awk commands . Help will be really appreciated. – user7515829 Feb 04 '17 at 21:00
  • I am sorry I misread your question, I have sorted all the lines on the basis of 4th column. – Akash Feb 05 '17 at 07:21
  • Thats fine Akash. As i am stucked on the logic of this question.Now i think ,it can be done by using awk command .I am confused in how to use the array and loop for this. – user7515829 Feb 05 '17 at 09:23
0

I am sorry for giving a wrong interpretation of the question. So here is the final answer. It's simple:

  1. First use awk to get the third column of the file trial.txt and save it in a temporary file.
  2. Sort this temporary file.
  3. Read every line from the trial.txt and temporary file simultaneously. To do this read https://unix.stackexchange.com/questions/82541/loop-through-the-lines-of-two-files-in-parallel. Then from each input of the line from trial.txt replace its 4th column using awk with the line input from the temporary file. To do this take help from How to replace the nth column/field in a comma-separated string using sed/awk?. Store this in a new file and delete temp after this. Done!
Community
  • 1
  • 1
Akash
  • 939
  • 1
  • 8
  • 27