1

I have the following command for arranging a few lines in a file using sed and column:

:-3,+2!sed 's/- 2021/\&2021/' | sed 's/ 2021/\&2021/' | column -s '&' -t

This works fine. For example, the following buffer:



  a - 2021-01-01
  b     - 2021-04-05



Gets formatted into:

  a       2021-01-01
  b       2021-04-05

I would like to use this as part of a larger function. However, that does not seem to work. If I define it like this:

function Test()
  normal :-3,+2!sed 's/- 2021/\&2021/' | sed 's/ 2021/\&2021/' | column -s '&' -t
endfunction

And enter :call Test()<CR>, nothing happens. But if I enter the command directly, it works fine.

I have read about system(), but I don’t know yet how to pass lines into there, then removing the old lines from the buffer, etc. Is there any way to make the ! command work in functions?

0

2 Answers 2

2

Remove the normal; you want to run an Ex command, so just run it:

-3,+2!sed …

and note that you can define functions which take ranges (you'll need :execute … at that point).

1

Try this:

xnoremap <F3> :<c-u>call Test()<cr>

function Test() abort
    let shellcmd = 'sed ''s/- 2021/\&2021/'' | sed ''s/ 2021/\&2021/'' | column -s ''&'' -t'
    let oldlines = getline("'<", "'>") + ['']
    let @" = system(shellcmd, oldlines)
    normal! gvp
endfunction

Visually select your lines, then press <F3>.

For more info, see:

Your Answer

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

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