How to open copied file by VI

comphys 08/15/2018. 4 answers, 761 views

Say, I have 'a.txt'. I would like to copy the file and open the newly copied file using VI.

cp a.txt b.txt
vi b.txt

How to combine the two command in a command?

4 Answers

Filipe Brandenburger 08/15/2018.

You can use vi itself to do the copy, by opening a.txt then saving the contents to b.txt (effectively copying it) and then switching to b.txt.

Putting it all together:

vi -c 'w b.txt' -c 'e#' a.txt

This is equivalent to running vi a.txt, followed by the :w b.txt command (inside vi), which will save the contents to a file named b.txt. But vi will still be editing a.txt at this point, so you follow up with the :e# command, which means "edit alternative file" (or "edit last file") and given vi has just touched b.txt, it will switch to editing that file.

msp9011 08/15/2018.

using && operator

cp a.txt b.txt && vi b.txt

Kamaraj 08/15/2018.

You can write your own function and use that function. In the below example, you can use cp1 as a command.


$ cat test.txt
function cp1() {
  cp "${source_file}" "${destination_file}"
  vi "${destination}"

$ . ./test.txt    
$ cp1 a.txt b.txt 

Hielke Walinga 08/15/2018.

If you want a way to save you typing you can use bash build in functionality to repeat the last word of the previous command. You can do this by ALT+.

> cp a.txt b.txt
> vi ALT+.

Very useful, and reminds you of the dot operator of vim.

Happy golfing.

Related questions

Hot questions


Popular Tags