How to replace newlines with tab characters?

2020-07-02 09:37发布

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.

标签: shell unix sed awk
6条回答
该账号已被封号
2楼-- · 2020-07-02 09:56

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.

查看更多
Deceive 欺骗
3楼-- · 2020-07-02 10:02

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.

查看更多
Melony?
4楼-- · 2020-07-02 10:14

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楼-- · 2020-07-02 10:18

not sure about output you want

# awk -vRS="\n" -vORS="\t" '1' file
hi      hello   hallo   greetings       salutations     no more hello for you 
查看更多
在下西门庆
6楼-- · 2020-07-02 10:18
sed '$!{:a;N;s/\n/\t/;ta}' file
查看更多
姐就是有狂的资本
7楼-- · 2020-07-02 10:18
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.

查看更多
登录 后发表回答