Stephan
Stephan

Reputation: 43

How to sort file rows with vi?

I have to edit multiple files with multiple rows, and also everything is in three columns, like this:

#file

save    get    go
go      save   get
rest    place  reset

Columns are separated with tab. Is there any possible way to sort rows based on second or third column using vi?

Upvotes: 4

Views: 3721

Answers (5)

vicky
vicky

Reputation: 31

delimit the column using some char here I have | symbol as delimiter, once did with that you can use below command to sort specific column use -n if u want to sort numeric and its working on some version of vi and not on ubuntu vi :(

/|.*|/ | sort

Upvotes: 0

Kent
Kent

Reputation: 195169

sort by the 2nd col:

:sor /\t/ 

sort by the 3rd col:

:sor /\t[^\t]*\t/   

Upvotes: 4

romainl
romainl

Reputation: 196751

Second column:

:sort /\%9c/

Third column:

:sort /\%16c/

\%16c means "column 16".

Upvotes: 1

user849425
user849425

Reputation:

You can specify a pattern for sort. For example:

sort /^\w*\s*/

Will sort on the second column (the first thing to sort after matching the pattern).

Likewise

sort /^\w*\s*\w*\s*/

Should sort on the third column.

Upvotes: 0

Brad
Brad

Reputation: 11515

  1. Hi light the rows you want to sort with "V" command

  2. Use a bash command with "!" to work on the selection, like:

    !sort -k 10

Where the number is the column number where your second (sort) column starts.

vi will replace the selection with the output of the sort command - which is given the original selection.

Upvotes: 0

Related Questions