1

I want to print the file content based on sorting the 3rd column of sourcefile.

sourcefile.txt:

Manav Kumaom Fre
shailesh himadri aif
manisha Kailash mac
Ravi Jwala blu
Prakash Ojha Zan
Mahi Aulakh yep

I want to print the file content sorted on the basis of 3rd column in a new file:

Required output:

shailesh himadri aif
Ravi Jwala blu
Manav Kumaom Fre
manisha Kailash mac
Mahi Aulakh yep
Prakash Ojha Zan
Manisha Kuhar
  • 57
  • 2
  • 6
  • 2
    Please [edit] your question and clarify: i) what operating system are you using, ii) did you try `sort`? This is what it's for, did it not work? What part of this is giving you problems? – terdon Jun 18 '20 at 08:47

2 Answers2

3

Try this,

sort -k3 sourcefile.txt
  • -k to sort with the key position/field.
Siva
  • 9,017
  • 8
  • 56
  • 86
1

Since you tagged

set filename "sourcefile.txt"
set fh [open $filename r]
set data [split [read -nonewline $fh] \n]
close $fh
set sorted [lsort -index 2 -dictionary $data]
puts [join $sorted \n]

That sorts by the 3rd word of each line (-index 2) in dictionary order -- I'm assuming that each line is a valid list. That may be naive: this would be safer:

set lines [split [read -nonewline $fh] \n]
set data [lmap line $lines {split $line}]

output

shailesh himadri aif
Ravi Jwala blu
Manav Kumaom Fre
manisha Kailash mac
Mahi Aulakh yep
Prakash Ojha Zan
glenn jackman
  • 84,176
  • 15
  • 116
  • 168