首页 > 解决方案 > 如何通过在文件开头插入日期和一些文本来启动 vim?

问题描述

我正在编写一个 bash 脚本来创建类似这样的日志文件,其中最新的条目首先出现在文件中:

2019-07-26 Looks like SSD needs replacing
2019-07-25 db backup failed

如果命令行中没有包含文本,只需启动 vim。如果命令行中包含文本,请插入日期和该文本,例如

edlog db backup failed

从概念上讲,它在我的脑海中看起来像这样,但只有第一个 -c 命令按预期工作:

!/bin/bash
if [ $# -eq 0 ]
  then
    nvim ~/log.txt
else
  # :r will Insert date at top of file.
  # $\t moves to end of line and inserts a tab
  # $* appends contents of command line
  nvim -c ":r! date +\%F"  -c "$\t" -c "$*" ~/log.txt
fi                

标签: vim

解决方案


这是我的解决方案。我非常愿意接受批评和纠正。

#!/bin/bash
# Appends to a log file if you type a message, or
# just brings up vim in case you want to log several
# lines' worth
# Nothing added to command line, so just bring up vim:
if [ $# -eq 0 ]
  then
    nvim ~/Dropbox/log.txt
else
  # User entered something like this:
  #   edlog Extra backup last night due to OS update
  LINE="  $*"
  # Format date like 07/25/2019
  # Start inserting text after the date.
  # Insert all arguments on command line, like "Re-test db"
  # Then write out file, and quit back to shell
  nvim -c ":pu=strftime('%m/%d/%Y')" -c ":startinsert!" -c "norm a$LINE" -c "wq" ~/Dropbox/log.txt
fi

推荐阅读