I'm using vi on Ubuntu 12.10. Some files are quite long so when I want to go to the middle of the file, I have to page down or scroll down.

Is there a VIM shortcut to go to an exact line number?

1

4 Answers

:150 

will take you to line 150 in vi

:1500 

will take you to line 1500 in vi

As per the comments you may want to try

150G

to get to line 150. which is less key strokes then :150Enter if you aren't sure what line you are on try

 :set nu! 

notice the :

if you want to always see the line consider editing your vim profile. Most often

vi ~/.vimrc 

and add

:set nu! 

and write and quit

:wq #or you could use :x 

this can be done outside of vi. For example, if I want to delete line 5000 in a text file I could use a scripting language. For example, using sed it would be the following

sed -i '5000d;' inputFile.txt 

to delete line 10 to 20 it would be

sed -i '10,20d;' inputFile.txt 

notice the -i will edit the file in place. Without the -i it will goto stdout. Try it. you can redirect stdout to a file

sed '5001,$d;' inputFile.txt >> appenedFile.txt 

this might have a lot going on here for you. this deletes line 5001 to $. With $ being the end of the file. >> will append to a file. where as > creates a new file.

if you are curious how many lines are in a file you may want to type wc -l inputFile.txt

some of this may seem awfully trivial, but if you are trying to edit a file with 50,000 lines it may take vi a sweet minute to open and traverse. where if you know you just want to delete the last line you could use sed and do it in a fraction of the time.

sed can also search and replace inside a file as well. But perhaps awk, perl, or python might also be a viable solution.

but overall, you may wan to find a good tutorial on vi. thousands exist. I'd consult google. Perhaps find yourself a VIM Cheatsheat.

7

Other vim tips: in command mode

  • H goes to the top of the screen
  • M goes to the middle of the screen
  • L goes to the bottom of the screen
  • gg goes to the first line
  • G goes to the last line

take a few minutes and start reading this document. It reward you in the long run for efficiency in editing especially config file.

1

From an opened terminal, in a bash shell, simply edit your file by running:

$ vi +N yourfile 

Where N is the line number.

For viewing (more or less;):

$ less +N yourfile $ more +N yourfile 

The sign + mean command to run at start. So if command is only a number, then vi, less and more, will jumps to this as line number.

But you may also use /regex for finding the first occurence of a specific string or regex:

$ less +/Error logfile $ less -i +/error logfile # -i Causes less's searches to ignore case $ vi +/open.*myfile myprog... 

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy