Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I swap two columns using sed?

Tags:

sed

I'm trying to change the text in a file from this:

file.txt,c:\path\to\file
file.txt,c:\path with spaces\to\file
file.txt,c:\path\to\file with spaces
file.txt,c:\path\to\file with spaces
file.txt,c:\path\to\file with spaces

To this kind of output (one path to the file):

c:\path\to\file\file.txt
c:\path with spaces\to\file\file.txt
c:\path\to\file with spaces\file.txt
c:\path\to\file with spaces\file.txt
c:\path\to\file with spaces\file.txt

This ALMOST works but requires a ',' on the end of the line :

sed 's@\(.*\),\(.*\),\(.*\)@\2,\1,\3@g' file

Any help would be appreciated, I don't know sed all that well...

EDIT

This worked for me but I would still like to add a "\" in there:

sed 's@\(.*\),\(.*\)@\2,\1,\3@g' file
like image 419
Mike Q Avatar asked Dec 10 '12 20:12

Mike Q


1 Answers

Escape the backslash, \\.

sed 's/^\(.*\),\(.*\)$/\2\\\1/g' file
                       --^^--

Also, you only need two capturing groups.


But since I'm more an awk guy.

awk -F, '{ print $2 "\\" $1 }' file
like image 181
Alexander Avatar answered Oct 05 '22 23:10

Alexander