Wednesday, April 6, 2011

Vim Visual Selection Tricks

# You can use filters and vim's execution do some powerful things.
# A filter is any standard UNIX program (sort, awk, grep, cut, paste, sed ...) that can read from stdin and write to stdout.
# Vim's execution mode lets you read in or replace text with the output of a program. If you make a visual selection (say,
# using V or C-V), and hit :, your command prompt will immediately be :'<,'>, which means "Apply whatever command follows
# to the lines included in the visual selection." At this point, you can write !foo to replace the text with the output of
# program foo.

# For example, to sort the text by the python column, select it, hit :, and enter !sort -k5. The whole command will look like
:'<,'>!sort -k5
# Running it will produce:

a b cd 1 p
b b cd 2 y
c b cd 3 t
d b cd 4 h

# Results in:

d b cd 4 h
a b cd 1 p
c b cd 3 t
b b cd 2 y

# For more complex tasks, awk is your friend. A command like
:'<,'>!awk '{ print $1, $3, $2, $4, $5 }'

a cd b 1 p
b cd b 2 y
c cd b 3 t
d cd b 4 h

# will flip the second and third columns (but note that inter-column spacing is collapsed).
# To do maths on a column, try something like
:'<,'>!awk '{ sub($4, $4*2+1); print }'

a b cd 3 p
b b cd 5 y
c b cd 7 t
d b cd 9 h

# Could get the same result with perl if there is only one column of numbers:
:'<,'>!perl -pe 's/\d+/$&*2+1/e'

# To flip the visual selection just select the rows and then:

d b cd 4 h
c b cd 3 t
b b cd 2 y
a b cd 1 p

# This pipes the lines through the unix 'reverse cat' program.

These ideas were taken from here:

Sand here:

No comments:

Post a Comment