如何使用bash将多行拼成一行?

时间:2017-10-26 07:57:51

标签: linux string bash sed

所以我的代码看起来像这样:

else if(between(pay,1260,1280))
{
    return 159;
}
else if(between(pay,1280,1300))
{
    return 162;
}
else if(between(pay,1300,1320))
{
    return 165;
}

但我希望它看起来像这样:

else if(between(pay,1260,1280)){return 159;}
else if(between(pay,1280,1300)){return 162;}
else if(between(pay,1300,1320)){return 165;}

我可以用bash做到这一点吗?如果没有,我可以使用哪种语言?

完整代码超过30,000行,我可以手动完成,但我知道有更好的方法。我想说'sed'命令可以帮助我混合使用正则表达式,但据我所知,这可以带给我。

P.S请忽略这一次未经优化的情况。

2 个答案:

答案 0 :(得分:0)

这可能适合你(GNU sed):

sed '/^else/{:a;N;/^}/M!ba;s/\n\s*//g}' file

在模式空间中收集所需的行,并在遇到结束标记时删除所有换行符和后续空格,即以}开头的行。

答案 1 :(得分:0)

关注awk也可以帮助你。

awk -v RS="" '{
$1=$1;
gsub(/ { /,"{");
gsub(/ }/,"}");
gsub(/}/,"&\n");
gsub(/ else/,"else");
sub(/\n$/,"")
}
1
'  Input_file

输出如下。

else if(between(pay,1260,1280)){return 159;}
else if(between(pay,1280,1300)){return 162;}
else if(between(pay,1300,1320)){return 165;}

编辑: 现在也为解决方案添加说明。

awk -v RS="" '{      ##Making RS(record separator) as NULL here.
$1=$1;               ##re-creating first field to remove new lines or space.
gsub(/ { /,"{");     ##globally substituting space { with only { here.
gsub(/ }/,"}");      ##globally substituting space } with only } here.
gsub(/}/,"&\n");     ##globally substituting } with } and new line here.
gsub(/ else/,"else");##globally substituting space else with only else here.
sub(/\n$/,"")        ##substituting new line at last of line with NULL.
}
1                    ##motioning 1 here as awk works on method of condition and action.
                     ##So here I am making condition as TRUE and then not mentioning any action so be default print of current line will happen.
'  Input_file