Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

removing new line character from incoming stream using sed

Tags:

shell

sed

csh

I am new to shell scripting and i am trying to remove new line character from each line using SED. this is what i have done so far :

printf "{new\nto\nlinux}" | sed ':a;N;s/\n/ /g'

removes only Ist new line character. I somewhere found this command :

printf "{new\nto\nlinux}" | sed ':a;N;$!ba;s/\n/ /g'

but it gives :"ba: Event not found."

if i do:

printf "{new\nto\nlinux}" | sed ':a;N;s/\n/ /g' | sed ':a;N;s/\n/ /g'

then it gives correct output but i am looking for something better as i am not sure how many new character i will get when i run the script. incoming stream is from echo or printf or some variable in script. Thanks in advance

like image 887
nav_jan Avatar asked May 16 '12 12:05

nav_jan


2 Answers

To remove newlines, use tr:

tr -d '\n'

If you want to replace each newline with a single space:

tr '\n' ' '

The error ba: Event not found is coming from csh, and is due to csh trying to match !ba in your history list. You can escape the ! and write the command:

sed ':a;N;$\!ba;s/\n/ /g'  # Suitable for csh only!!

but sed is the wrong tool for this, and you would be better off using a shell that handles quoted strings more reasonably. That is, stop using csh and start using bash.

like image 93
William Pursell Avatar answered Oct 07 '22 11:10

William Pursell


This might work for you:

printf "{new\nto\nlinux}" | paste -sd' '            
{new to linux}

or:

printf "{new\nto\nlinux}" | tr '\n' ' '            
{new to linux}

or:

printf "{new\nto\nlinux}" |sed -e ':a' -e '$!{' -e 'N' -e 'ba' -e '}' -e 's/\n/ /g'
{new to linux}
like image 7
potong Avatar answered Oct 07 '22 13:10

potong