合并具有相同起始模式的多行

时间:2018-12-12 11:09:56

标签: shell awk

我有一个文本文件,其内容如下。

-country
-the
-elections
+countries
+be
+a
+chance
-the
-means
-we
+need
+people’s
+choice
-democracy
+democracies
-elections
-there
+increases
+their

我想要具有相同起始样式的合并线。对于上述文件输出应为

-country -the -elections 
+countries +be +a +chance
-the -means -we
+need +people’s +choice
-democracy
+democracies
-elections -there
+increases +their

我尝试过

sed '/^-/{N;s/\n/ /}' diff_1.txt

但是它的合并行以-开头,并且这也不符合预期。

3 个答案:

答案 0 :(得分:1)

您可以使用此import MyComponent from './components/my-component' export default ({ Vue, options, router, siteData }) => { Vue.component('MyComponent', MyComponent) }

awk

awk '{ch=substr($0,1,1)} p != ch{if (NR>1) print s; s=""}
{p=ch; s = (s != "" ? s " " $0 : $0)} END{print s}' file

答案 1 :(得分:0)

这是另一个awk:

awk '{c=substr($0,1,1); printf (c==t ? OFS : ORS) $0; t=c}'

但是,这将在所有内容之前引入一个空行。

您可以通过以下方式摆脱这种情况:

awk '{c=substr($0,1,1); printf (c==t ? OFS : (NR==1?"":ORS)) $0; t=c}'

答案 2 :(得分:0)

使用Perl

> cat amol.txt
-country
-the
-elections
+countries
+be
+a
+chance
-the
-means
-we
+need
+people’s
+choice
-democracy
+democracies
-elections
-there
+increases
+their
> perl -lne ' $c=substr($_,0,1) ;$tp=$tc;$tc.="$_"." "; if($.>1 and $p ne $c) { print "$tp";$tc=$_." ";} $p=$c; END { print "$tc" } ' amol.txt
-country -the -elections
+countries +be +a +chance
-the -means -we
+need +people’s +choice
-democracy
+democracies
-elections -there
+increases +their
>

或更短

> perl -lne ' $c=substr($_,0,1) ;$tp=$tc;$tc.="$_"." "; print "$tp" and $tc=$_." " if $.>1 and $p ne $c ; $p=$c; END { print "$tc" } ' amol.txt