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
1
  • 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, 2020 at 8:47

2 Answers 2

3

Try this,

sort -k3 sourcefile.txt
  • -k to sort with the key position/field.
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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .