0

I am trying to edit a json file, and I need to take out the lines starting and ending with {% and %} respectively and move them to the beginning of the file. I need to do it at different places in a single file and repeat it for a lot of files, hence I am looking for a single command to this for one place and then I can repeat it again and again.

Ex. Current file:

{% data 1 %}

{

  "data1": [

     detail1a: data detail 1a

     detail1b: data detail 1b

  ]

}

{% data 2a %}

{% data 2b %}

{

  "data2": [

     detail2a: data detail 2a

     detail2b: data detail 2b

  ]

}

{% data 3a %}

{

  "data3": [

     detail3a: data detail 3a

  ]

}

In this file, i want to remove all the data xa/xb lines and paste them at the beginning of the file like:

{% data 1 %}

{% data 2a %}

{% data 2b %}

{% data 3a %}
<rest of the lines>% data 3a %}

Then I can use :%s/^\(\s\+\)]\n}\n{$/\1],/g to remove the }{ to join it as a single execution.

I can do /^{%.*%}$ to get the line but how do I cut it and move it to line 0 (pushing down whatever is at line 0 already).

Any help appreciated.

PS: This is my first post in stackechange and I tried looking for all the existing posts to my best. The closet I found is this (Cut line, trim it and then paste it on another line) but it doesn't solve my purpose. Please excuse if I missed some norms.

1

The most direct solution is a :global command:

:g/^{%.*%}$/m0

The slight problem is that this leaves the lines in reverse order. A simple solution is just to run it again! (By pressing :UpEnter.)

If that seems inelegant to you, it's also possible to do it in a single pass. Here's one way:

:2mark a
:2,$g/^{%.*%}$/normal! dd'aP

Noting that the first line is already in the correct place, we first set a mark a on the second line. We then run a :normal command on each of the remaining matching lines to move each of them above the line we just marked.

For more details, see:

  • :help :global
  • :help :move
  • :help :normal
  • :help cmdline-ranges
  • Worked like a charm! Thank you so much for your quick help. – GvR Feb 27 '18 at 0:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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