1

How do I open all the files in a given directory using vim, in the reverse alphabetical order? The command -

vim *

would open all files in alphabetical order. How can I iterate through the files using :n in the opposite order? I found the use of tac here, another solution here that displays the file content here, and a solution for emacs here, but they are not solutions for vim.

1

The general idea may be to reverse what * yields:

printf '%s\n' * | tac

and use this with xargs to spawn vim. Two problems with this:

  1. In general file names may contain newline characters, so it's better to separate with null characters and use xargs -0.

  2. vim spawned by xargs in a pipe will complain about input not being from a terminal. Strange things may happen. If your xargs supports -o (reopen stdin as /dev/tty in the child process before executing the command) then use it.

The whole solution then:

printf '%s\0' * | tac -s "" | xargs -0o vim

Notes:

  • tac is not required by POSIX; xargs may not support the options used. The entire approach is not portable.
  • Empty string as option-argument to tac -s seems to set null character as separator without passing any null character explicitly (it may be problematic).
  • There is ARG_MAX limit, you cannot run a command that is longer. If there are many files, the expansion of * may exceed the limit, you may get Argument list too long. If printf is a builtin in your shell then the limit may not apply at this point. Still it applies when xargs tries to spawn vim. xargs will detect this and run two or more vim processes in sequence, if needed. This, however, may not be what you want. Hopefully, since you're going to manually iterate with :n, I expect the number of files is not that big, so ARG_MAX won't be a problem.
5
  • I get an Illegal variable name error. – V-Red Aug 19 '19 at 21:04
  • Sorry for not mentioning, I am using a tcsh shell. – V-Red Aug 20 '19 at 15:41
  • Yes more than the type of shell, it seems to be a problem with the quotes – V-Red Aug 20 '19 at 15:44
  • printf '%s\n' * | tac reverses the order, but printf '%s\n' * | tac -s "\0" does not. – V-Red Aug 20 '19 at 16:14
  • @V-Red The command in the current version of my answer works for me in tcsh. – Kamil Maciorowski Aug 20 '19 at 16:20

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.