开发者

Swapping 2 columns with Emacs

I have 2 columns, separated by comma. How can I swap those columns with Emacs?

I have the following:

开发者_开发百科  column 1,column2
  x1,x2
  y1,y2
  f1,f2

and I want it like this:

 column2,column 1
 x2,x1
 y2,y1
 f2,f1


Use M-x query-replace-regexp and then:

\(.+\),\(.+\)

as replace regexp and

\2,\1

for replacement.


In Emacs, you need to escape grouping parentheses with \. So, above regexp would be usually written as

(.+),(.+)

which means that you want everything before comma in first group and everything after comma in second group.

\2,\1

means: write second group, then comma, then first group.


While you can apply techniques given by other people, you can also use the org-mode tables. Once you convert the data into org-mode table, it is very easy to swap the columns by simple keystrokes. You can have M-x org-mode, select the region then do M-x org-table-convert-region, and then M- on the right most column. I am not sure, how to export the data as CSV, but that should be very easy for you with replace-regexp. This can be helpful: http://www.gnu.org/software/emacs/manual/html_node/org/Tables.html#Tables


Similar to the answer given by @darioo, type the following into the top of your buffer:

(query-replace-regexp "\\(.*?\\),\\(.*\\)" "\\2,\\1")

Then, put your cursor at the end of this line and press ctrl-x, ctrl-e.

You will have an interactive search-and-replace for which you press the space bar to make the change, and press ctrl-g to quit. If you press ! (exclamation mark) then the search will cease being interactive and take place on all matching text.

If you want to reverse the changes then press M-x (usually ESC followed by x) and type undo and press enter.


Emacs has a rectangular selection mode, see for example: http://emacs-fu.blogspot.com/2008/12/working-with-rectangular-selections.html

Even better, if you enable cua-mode, entering Ctrl-Enter will put you in rectangle selection mode that is very easy to use.

http://trey-jackson.blogspot.com/2008/10/emacs-tip-26-cua-mode-specifically.html


Use a macro !

  • Go to the first line of the buffer
  • Start recording a macro (F3)
  • Move to the beginning of the line (^a)
  • Search for comma (^s ,)
  • Transpose (M-t)
  • Move cursor down one line
  • Stop recording macro (F4)

Select the rest of the lines and:

M-x apply-macro-to-region-lines

UPDATE: This doesn't work properly if you have multiple words in a column. Looking for a more general solution...

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜