How can I remove a line-feed/newline BEFORE a pattern using sed

匿名 (未验证) 提交于 2019-12-03 09:06:55

问题:

The title already states it:

I want to use some linux one liner (e.g. sed)

to transform

Anytext { 

into

Anytext{ 

Can this be done using sed or if not with sed then with an awk one liner ?

回答1:

Sure,

sed 'N;s/\n{/{/' 

Or a more thorough version:

sed ':r;$!{N;br};s/\n{/{/g' 

Here, :r sets a label that we can refer to in order to create a loop;

$!{...} executes the given set of commands for every line except the last one;

N;br are two commands the get executed in the loop: N appends a new line to the pattern space, and br branches back to the label r, completing the loop.

Then you have all of your file in pattern space when you run the final command:

s/\n{/{/g 

You can see the difference between the two approaches if you try it on something like

Anytext { { { 


回答2:

One way using sed:

sed -ne '$! N; /^.*\n{/ { s/\n//; p; b }; $ { p; q }; P; D' infile 

A test. Assuming infile with content:

one Anytext { two three { four five { 

Output will be:

one Anytext{ two three{ four five{ 


回答3:

If the intention is to remove the newline from a \n{ sequence bbe seems to be the simplest tool to use:

bbe -e 's/\n{/{/' infile 


回答4:

This might work for you (GNU sed):

sed ':a;$!{N;/.*\n{/ba};s/\n{/{/g;P;D' file 


回答5:

Using awk

cat file one Anytext { two three { four five { 

awk '{printf (!/^{/&&NR>1?RS:x)"%s",$0} END {print ""}' file one Anytext{ two three{ four five{ 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!