开发者

How to replace newlines with tab characters?

I have pattern like belo开发者_JAVA百科w

hi
hello
hallo
greetings
salutations
no more hello for you

I am trying to replace all newlines with tab using the following command

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

but it's not working.

Could anybody please help? I'm looking for a solution in sed/awk.


tr is better here, 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.


not sure about output you want

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


sed '$!{:a;N;s/\n/\t/;ta}' file


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.


paste -s

-s Concatenate all of the lines of each separate input file in command line order. The newline character of every line except the last line in each input file is replaced with the tab character, unless otherwise specified by the -d option.


You are almost there with your sed script, you'd just need to change it to:

sed -e "s/\n/\t/g"

The \ is enough for escape, you don't need to add _ And you need to add the / before g at the end to let sed know that this is the last part of the script.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜