AKM
AKM

Reputation: 6575

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

Upvotes: 8

Views: 3078

Answers (5)

aartist
aartist

Reputation: 3236

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

Upvotes: 6

Roberto Aloi
Roberto Aloi

Reputation: 30995

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...

Upvotes: 3

ustun
ustun

Reputation: 7031

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

Upvotes: 3

PP.
PP.

Reputation: 10864

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.

Upvotes: 4

darioo
darioo

Reputation: 47193

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.

Upvotes: 12

Related Questions