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?

2 Answers2

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).

D. Ben Knoble
  • 26,070
  • 3
  • 29
  • 65
1

Try this:

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

function Test() abort let shellcmd = 'sed ''s/- 2021/&amp;2021/'' | sed ''s/ 2021/&amp;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:

user938271
  • 5,947
  • 1
  • 15
  • 24