Reputation: 10865
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
Reputation: 967
If you are ok with python(installed in your os and activated in vim) you can:
edit the text to:
a=[your list];print(len(a));
for x in a:print(x)
enter visual mode and select all the text
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
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