Shell – Opening most recently modified file in vim

datefilespipeshellvi

The following commands work

$ ls -1t | head -1
git_sync_log20180924_00.txt

$ vi git_sync_log20180924_00.txt

But this does not

$ ls -1t | head -1 | vi
Vim: Warning: Input is not from a terminal
Vim: Error reading input, exiting...
Vim: preserving files...
Vim: Finished.

How can I accomplish this (open most recently modified file in vi)?

Best Answer

vi -- "$(ls -t | head -n 1)"

(that assumes file names don't contain newline characters).

Or if using zsh:

vi ./*(om[1])

Or:

vi ./*(.om[1])

To only consider regular files.

vi ./*(.Dom[1])

To also consider hidden files (as if using ls -At).

Those work regardless of what characters or byte values the file names may contain. For a GNU shell&utilities equivalent of that latter one, you can do:

IFS= read -rd '' file < <(
  find . ! -name . -prune -type f -printf '%T@\t%p\0' | sort -zrn | cut -zf2-) &&
  vi "$file"