1

I have a file foo.txt with just a one line ab. I want to launch Vim in such a way that it will open this file, swap characters using xp, and then save it as bar.txt.

Something like this:

gvim foo.txt xp :wq > bar.txt 

I'm not sure it is possible. Any suggestions?

2 Answers 2

3

You can use Ex commands (linux version using pipes):

printf '%s\n' 'normal! xp' 'saveas bar.txt' 'q!' | ex foo.txt 

vim -e and vim -E can usually be used as a substitute for ex.

Or use a custom script:

gvim -S mycmds.vim foo.txt 

Where the file contains arbitrary Ex commands:

normal! xp saveas bar.txt quit! 
7
  • Hello, thanks. The former solution doesn't work for some reason; Command Prompt gives me an error 'ex' is not recognized as an internal or external command, operable program or batch file.. The second version doesn't really swap characters; bar.txt contains only a. Commented Sep 5, 2020 at 14:49
  • 2
    The first assumes you have ex (comes with vim, maybe not with gvim?). As for the second, I find that odd.. it could be a cursor issue? You might want 1 then normal! 0xp or some other sequence to position the cursor appropriately. Commented Sep 5, 2020 at 15:25
  • 2
    ex is required on posix systems; again, not sure about the windows install of vim. The issue with a non-default vimrc is likely some autocommand restoring a file position or some other thing. You can use -u and other options to force the default vimrc, none, or some other combination. @johnc.j. Commented Sep 5, 2020 at 15:56
  • 2
    If Ex is not found, you can try to substitute ex by vim -e. In GNU/Linux systems, Ex is just Vim in Ex mode. Also, there are other tools to do this job, for example, Sed. Commented Sep 5, 2020 at 16:52
  • 2
    @Quasímodo agreed; this is one of those cases where sed really is right (i.e., we're not trying to edit in place with a stream editor 🙄—excuse the rant) Commented Sep 5, 2020 at 16:57
1

Here's a couple more techniques you can use.

Using -c or +

You can pass ex commands into Vim by using the -c command line option or its shortened version, +:

vim foo.txt +'normal! xp' +':wq! bar.txt' 

(Note that the :wq! command can take a filename argument: it's slightly more concise to use this rather than :saveas and :q! separately.)

Using a script with -s

Similar to the -S option described by @D. Ben Knoble, you can use the -s option to run a script interpreting its contents as keystrokes.

Create a file named e.g. my_script with the following contents, being sure to press Return at the end of the line so that the file contains two lines in total (the second being a blank line):

xp:wq! bar.txt 

Then run this script:

vim foo.txt -s my_script 

See also the -w option, which you can use to record a script that can be executed with the -s option.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.