How can I replace a newline (“\n“) with a space (““) using the sed command?
I unsuccessfully tried:
sed 's#\n# #g' file
sed 's#^$# #g' file
How do I fix it?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Use this solution with GNU
sed:This will read the whole file in a loop (
':a;N;$!ba), then replaces the newline(s) with a space (s/\n/ /g). Additional substitutions can be simply appended if needed.Explanation:
sedstarts by reading the first line excluding the newline into the pattern space.:a.N.$!ba($!means not to do it on the last line. This is necessary to avoid executingNagain, which would terminate the script if there is no more input!).Here is cross-platform compatible syntax which works with BSD and OS X’s
sed(as per @Benjie comment):As you can see, using
sedfor this otherwise simple problem is problematic. For a simpler and adequate solution see this answer.