How to replace newlines with tab characters?

2020-07-02 10:11发布

问题:

I have pattern like below

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.

回答1:

not sure about output you want

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


回答2:

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.



回答3:

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


回答4:

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.



回答5:

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.



回答6:

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.



标签: shell unix sed awk