I want to replace ^M\n part by space in a CSV file using sed command in Linux.....

I used sed 's/\n/ /g' but it is only replacing \ and not the other part.....

To be more descriptive, i am using query like

| sed "s/'/\'/;s/\t/\",\"/g;s/^/\"/;s/$/\"/;s/\n//g" > file.csv

where the query result will be collected in csv file. but i can see that there are these \n characters coming in the csv file ...and i want to remove them. so ....i need to change the sed command accordingly ....that instead of \n i should get space characters......

  • Do you want to remove DOS line endings completely so that the result is on a single line, or do you just want to replace the carriage return (^M)? sed can not replace the actual newline (\n) because it won't see it. To convert the file to a Unix text file, use dos2unix on it. Edit your question with an example of what you have and what you'd like to get. Until then, the question is unclear. – Kusalananda Aug 9 '18 at 8:00
  • Why must it be using sed? There may be better and easier alternatives. – roaima Aug 9 '18 at 9:41
  • 1
    Some (or decently) more background info would help. I faintly remember MS EXCEL using \n to break text within cells, so we might not be talking of full lines here. – RudiC Aug 9 '18 at 10:11

I faced this issue even after doing dos2unix. I was able to resolve this with the below code.

sed -i  "s/\r/ /g" <fileName>
  • ^M is ctrl+r, so replace \r by space in file
| improve this answer | |

To replace DOS line-endings with spaces in the file file:

dos2unix file
tr '\n' ' ' file >newfile

This first converts the file to a Unix text file, and then replaces each newline with a space. The result is written to the new file newfile.

In one step (without modifying file):

dos2unix <file | tr '\n' ' ' >newfile

Slightly unsafe (as it deletes all carriage returns in the file even if they are not part of a DOS line ending (does not modify file though)):

tr -d '\r' <file | tr '\n' ' ' >newfile
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.