0

Hi eveyone. I am trying to read a file using vi editor and sort its content inside the file alphabetically which is only names on CAPITAL LETTERS, second field (JOHN, MIKE, JAYSON and TYLER).
The file is smth like this inside:
1:JOHN:Morgan:90:24
2:MIKE:Smith:95:11
3:JAYSON:Ty:99:9
4:TYLER:Edward:89:5

This is my vi script:

file="/home/students/domie/wine.txt"
while IFS=: read -r f1 f2 f3 f4 f5
do
        tput cup $f1 0 ;echo  "$f2 $f1 $f3 $f4 $f5"
done <"$file"

I came up to here to sort them, but this only switches places of f2 with f1.
Can someone help me?
thank you

Edited by endri_1

2
Contributors
3
Replies
18
Views
3 Years
Discussion Span
Last Post by endri_1
0

I've never really messed with vi/vim scripts, other than making a few minor modifications to my .vimrc startup file.

Using vim, you could sort the file using the command :sort.
That will sort the file in exactly the manner you have described. It's only a simple alphabetic sort, so there is no need to pass any parameters.
So you start with this:

JOHN:Morgan:90:24
MIKE:Smith:95:11
JAYSON:Ty:99:9
TYLER:Edward:89:5

Running the :sort command will give you this:

JAYSON:Ty:99:9
JOHN:Morgan:90:24
MIKE:Smith:95:11
TYLER:Edward:89:5

Which is what you wanted isn't it?

From the terminal or a shell-script, you could use the sort utility:
e.g. Sort the file and write the sorted output to a different file:
sort ./file.txt -o ./sorted.txt

But offhand, I'm not sure how you'd go about calling the sort function in a vi/vim script. I really should look into scripting vim though. I currently have a few macros set up in vim to automate various repetetive tasks. But it would be good to be able to write scripts for some of them!

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.