开发者

How do I apply a command to every line in a selection in Vim and replace with the result (like a spreadsheet)?

开发者 https://www.devze.com 2023-03-20 05:24 出处:网络
I have a table of values (actually written in LaTeX markup) and I can select one column only using Ctrl+Q

I have a table of values (actually written in LaTeX markup) and I can select one column only using Ctrl+Q

For example,

% Select the second column only ....
1.75130211563   & 0.0299693961831 \\
1.72144412106   & 0.0181406611688 \\
1.92102386609   & 0.0247758598737 \\
1.56512790839   & 0.0137107006809 \\
1.75263937567   & 0.017155656704  \\
1.99501744437   & 0.39550649953   \\
1.96862597164   & 0.030198328601  \\
...

I'd like to reduce the number of decimal places of the selected numbers only (i.e. for each number selected I apply round(NUMBER * 100)/100 to get, for example, the number rounded to 2 decimal places). To do this, I need to first have a variable to refer to NUMBER (the number on that line) as well as replace the current selection with the output.

How do I do this?

Also if this isn't possible, I can copy the column into an actual spreadsheet progra开发者_如何学Cm and edit it there, but how do I paste it back in place?

Update: I've accepted an answer. It isn't as neat as I had hoped, but it does make sense. Thanks!

Another update: To paste a column in from an external spreadsheet, paste the column into a :new buffer, select the data using Ctrl+Q and yank into a register. Move to the top line and appropriate column in the table of data and paste in with P.


Are you looking for this ?

:'<,'>s#\%V\d*\.\d\+#\=round(str2float(submatch(0))*100)/100#g


This seems to work:

:'<,'>:s/\d\+\.\d\+/\=printf("%.2f", str2float(submatch(0)))/

I.e. visually select the first column and issue the command above.

% Select the second column only ....
1.75   & 0.0299693961831 \\
1.72   & 0.0181406611688 \\
1.92   & 0.0247758598737 \\
1.57   & 0.0137107006809 \\
1.75   & 0.017155656704  \\
2.00   & 0.39550649953   \\
1.97   & 0.030198328601  \\
0

精彩评论

暂无评论...
验证码 换一张
取 消