Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I save any file with a space within its filename with vi?

Tags:

vim

I mostly use vim from the terminal by vi command.

I want to create and save a file named something like getting started.txt (there is space between two words). I tried two methods:

Method #1

:sav getting started.txt

but I got an error : E172: Only one file name allowed

Method #2

:sav "getting started.txt"

This time I got : E471: Argument required

How can I achieve what I want?

like image 327
Santosh Kumar Avatar asked Jun 15 '12 20:06

Santosh Kumar


People also ask

Can you put a space in a file name?

Leading (before the filename) and trailing (after the filename) spaces in file or folder names also aren't allowed. If you're using Office 2010, you can't use "&" in file and folder names. These names aren't allowed for files or folders: .

How do you put spaces in file names?

Use quotation marks when specifying long filenames or paths with spaces. For example, typing the copy c:\my file name d:\my new file name command at the command prompt results in the following error message: The system cannot find the file specified. The quotation marks must be used.

How do you handle a filename with space in Unix?

There are two main ways to handle such files or directories; one uses escape characters, i.e., backslash (\<space>), and the second is using apostrophes or quotation marks. Using backslash can be confusing; it's easy and better to use quotation marks or apostrophes.

How do I save a filename in vi?

To save a file, you must first be in Command mode. Press Esc to enter Command mode, and then type :wq to write and quit the file. The other, quicker option is to use the keyboard shortcut ZZ to write and quit. To the non-vi initiated, write means save, and quit means exit vi.


2 Answers

Escape the space character:

:sav getting\ started.txt
like image 110
pb2q Avatar answered Oct 06 '22 22:10

pb2q


Commenter @ib mentions fnameescape, here's how you can use it:

  1. Enter :save and a space.
  2. Press Ctrl-R then = to enter expression mode.
  3. Enter fnameescape("Your spacey, special character'y file name"). Tab expansion works, so you can probably do fnTabeTab.
  4. Press Enter to insert the escaped file name into your command line.

Poster iler.ml suggests a function to do this easily (I've modified his code slightly). Put this in your .vimrc:

" :W and :Save will escape a file name and write it
command! -bang -nargs=* W :call W(<q-bang>, <q-args>) 
command! -bang -nargs=* Save :call Save(<q-bang>, <q-args>) 

function! W(bang, filename) 
    :exe "w".a:bang." ". fnameescape(a:filename) 
endfu 

function! Save(bang, filename) 
    :exe "save".a:bang." ". fnameescape(a:filename) 
endfu 
like image 29
Leif Arne Storset Avatar answered Oct 06 '22 22:10

Leif Arne Storset