2
#!/usr/bin/env bash
# scp /tmp/abc.sh SERVER1:~/bin && ssh SERVER1 "~/bin/abc.sh"
echo "Hello Stack Exchange"
echo "thanks for the help

I would like to be able to use a keyboard mapping to be able to do <leader>r when my cursor is on line 2 and run the command in the bash shell. To do this, I need to be able to remove the # at the start of line two. :.w writes the whole line and it appears there is no way to use :w ! bash on a partial line. I've also tried :.w !sed "s/^# \(.*\)/\1/" but sed appears to have a problem with the # as part of command (E194).

It seems this should be relatively easy but I'm at my wits end. I'm running a Mac with Bash 5.2. Any help appreciated.

2
  • Funny I didn't think of this earlier, but the easiest solutions is to just put a multiple line bash comment at the start of the file and then have my little macros be one per line and execute them normally. Feb 19 at 8:54
  • Bash doesn't really have multiline comments so be careful with that strategy.
    – romainl
    Feb 19 at 9:00

1 Answer 1

2

Indeed you can't feed a partial line to :w ! or any other Ex command.

But you can use a bunch of vimscript functions to get a functionally identical outcome:

nnoremap <leader>r <Cmd>echo system('bash', substitute(getline('.'), '^#*\s*', '', ''))<CR>
  • :help getline() grabs the content of the given line(s), here it is the content of the current line,
  • :help substitute() changes whatever needs to be changed in the given line, here we remove eventual leading comment and whitespace, which makes the mapping work the same on commented and uncommented lines,
  • the result is passed to :help system() as input.

Note that quoting and escaping issues are easy to come by when dealing with the shell. I would recommend you read help system() carefully.

2
  • Many thanks for this. I'll have a read of the system documentation as it will help me get a better grasp of what is going on. I'll comment more once I've given it a try. Feb 20 at 13:21
  • It works perfectly. Many thanks! Since I'm new and don't have any reputation I can't vote the answer up, but if/when I can I will. Feb 20 at 13:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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