tomcam
tomcam

Reputation: 5285

How can I start vim by inserting the date and some text at the beginning of the file?

I'm working on a bash script to create log files something like this, where the latest entry appears first in file:

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

If no text is included on command line, just start vim. If text is included on the command line, insert date and that text, e.g.

edlog db backup failed

Conceptually it looks like this in my head but only the first -c command works as expected:

!/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                

Upvotes: 0

Views: 243

Answers (2)

D. Ben Knoble
D. Ben Knoble

Reputation: 4673

A quasi-vim centric solution:

date > file
echo "$@" >>file
vim file +'0join'

Using vim commands:

vim +'0r !date' +'0d' +"normal! A<Tab>$@"

Where <Tab> is a literal tab character.

Or with ex:

ex <<EOF file
0r !date
0d
normal! A<Tab>$@
wq
EOF

Upvotes: 0

tomcam
tomcam

Reputation: 5285

Here's my solution. I'm very much open to criticism and corrections.

#!/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

Upvotes: 1

Related Questions