Monday, November 20, 2006

Sample Ex/Vim Ranges

Here we go.

:%s/[a-z]/\u&/g

Substitute in all lines (the range defined by '%') all lower case latin letters ('[a-z]') with upper case letters ('[A-Z]'). Substitute in all lines (the range defined by '%') every lower case latin letter ('[a-z]') with upper-case letter ('\u&', see for more info :h s/\u).

:<'>' w new_file_from_selection.txt

Write ('w') all selected lines ("<'>'") into new_file_from_selection.txt. (You do not need to type that "<'>'" thing. Select lines in visual mode (entered by Shift-V) and then press ':' - vim will put the <'>' in prompt line for you)

:5,+99 w new_file.txt

Write ('w') to the file "new_file.txt" lines: 5th and next 99 ones included, total of 100 lines. (Provided that the actual file has minimum 1054 lines).

:0,$ ! tac

Filter ('!') all lines ('%' is simple shortcut for '0,$') through the external application 'tac'. The filter command would then replace all affected lines with the output of the application - in that case the lines would reappear in inverse order, thanks to the 'tac' command. ('tac' is of course opposite of 'cat'. man tac.).

:<'>' ! wc -l

That would replace all selected (in visual mode) lines with the count of selected lines, as counted by 'wc -l'.

And to conclude, the most useless (unless you're vim scripting addict) range example:

:.=

Print current line (range '.') number (command '=').

Edit1 Fix the uppercase command, as per anon comment. It should have been some real weird booze I had that day. N.B. more optimal is of course this: :%s/.\+/\U&/.

ZQ

2 comments:

Anonymous said...

This

:%s/[a-z]/[A-Z]/g

doesn't do what you say (convert lower to uppercase).

Try this instead:

:%!tr [a-z] [A-Z]

it also uses ranges and filters.

Ihar Filipau said...

Thanks, Anon.