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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With