Arun Arun - 7 months ago 8
Bash Question

Replace spaces in a file without changing those within fields

I have a CSV file with lines like,

5213 , 1395429467 , A , r7.sn-a8au-hp5e.gvt1.com , 4.31.38.18 , 1460706280 , John Doe


I know how to replace spaces in the file:
:%s/ //g
. It changes the entire file which has the spaces.

I want the last element
$7
to maintain its spaces, so
John Doe
has to keep being
John Doe
and no
JohnDoe
.

All together, the expected output is:

5213,1395429467,A,r7.sn-a8au-hp5e.gvt1.com,4.31.38.18,1460706280,John Doe


Can some one help me on how to achieve this?

Answer

You probably just need to replace every , (that is, space + comma + space) with a single ,:

sed 's/ , /,/g' file

Which retruns:

5213,1395429467,A,r7.sn-a8au-hp5e.gvt1.com,4.31.38.18,1460706280,John Doe