Qiang Li
Qiang Li

Reputation: 10865

vim how to transform text in this way

I want to transform this following text in a single line from

[12.2,3.3 ,8.1 ,9., 12.4]

to

5
12.2
3.3
8.1
9.
12.4

or from

[def,  abc , ghi ]

into

3
def
abc
ghi

So, essentially, removing [ and ], breaking elements based on , and remove leading or trailing spaces, and then put the number of elements as the first line (5 in the first example and 3 in the second) and each element in the following lines.

How to write a command to do this fast in vim?

Upvotes: 2

Views: 151

Answers (2)

Yasin Yousif
Yasin Yousif

Reputation: 967

If you are ok with python(installed in your os and activated in vim) you can:

  1. edit the text to: a=[your list];print(len(a)); for x in a:print(x)

  2. enter visual mode and select all the text

  3. just type :!python and it should transform your list to the desired shape, replacing the original

P. S.: the string need to be quoted in order for this to work

Upvotes: 0

Wray Zheng
Wray Zheng

Reputation: 997

Steps

1.Strip spaces in the list:

:s/ //g

2.Add number of elements to the start:

:s/\v\[(([^,]+)*[^\]]+)\]/\=len(split(submatch(1), ',')).','.submatch(1)/

3.Replace , with \r:

:s/,/\r/g

Results

After first step:

[12.2,3.3,8.1,9.,12.4]

After second step:

5,12.2,3.3,8.1,9.,12.4

After last step:

5
12.2
3.3
8.1
9.
12.4

Upvotes: 4

Related Questions