gpt4 book ai didi

linux - 如何使用 bash 将多行合并为一行?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:18:45 27 4
gpt4 key购买 nike

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

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 请忽略它是多么未优化,只有这一次。

最佳答案

以下 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

关于linux - 如何使用 bash 将多行合并为一行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46948766/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com