views:

242

answers:

4

hi i have pattern like below

hi
hello
hallo
greetings
salutations
no more hello for you

i am trying to replace all new lines with tab spaces using the following command

sed -e "s_/\n_/\t_g"

but its not working . could nybody pls help? i need the solution in sed /awk.

+2  A: 

Here tr is better, I think:

tr "\n" "\t" < newlines

As Nifle suggested in a comment, newlines here is the name of the file holding the original text.

Because sed is so line-oriented, it's more complicated to use in a case like this.

Telemachus
+1 Beat me by 40 seconds
Nifle
@Nifle: Also no `cat` here, but who's counting? :)
Telemachus
Might want to point out that 'newlines' is the textfile
Nifle
@Tele I'm a cat overuser, I admit that.
Nifle
is there a way to do this in sed itself?
Vijay Sarathi
-1 as i already know that we can do it with tr but i need how to do it in sed
Vijay Sarathi
@John: someone may be able to tell you how to do it in `sed`, but given that `sed` is so line-oriented, that's a bit like hammering in a screw.
Telemachus
+1  A: 

not sure about output you want

# awk -vRS="\n" -vORS="\t" '1' file
hi      hello   hallo   greetings       salutations     no more hello for you
ghostdog74
+1  A: 

You can't replace newlines on a line-by-line basis with sed. You have to accumulate lines and replace the newlines between them.

text abc\n    <- can't replace this one

text abc\ntext def\n    <- you can replace the one after "abc" but not the one at the end

This sed script accumulates all the lines and eliminates all the newlines but the last:

sed -n '1{x;d};${H;x;s/\n/\t/g;p};{H}'

By the way, your sed script sed -e "s_/\n_/\t_g" is trying to say "replace all slashes followed by newlines with slashes followed by tabs". The underscores are taking on the role of delimiters for the s command so that slashes can be more easily used as characters for searching and replacing.

Dennis Williamson
A: 
sed '$!{:a;N;s/\n/\t/;ta}' file
could you please also explain about the command you are using?
Vijay Sarathi
if its not the last line , get the next line join with pattern space, substitute the newline and then branch to :a and do the same for every line