Shell 组合具有相同起始模式的多条线
我有一个包含以下内容的文本文件Shell 组合具有相同起始模式的多条线,shell,awk,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 -
-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
但它的合并行以-开头,这也是错误的,并不像预期的那样。您可以使用此
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
这是另一个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}'
使用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
但它缺少文件的最后一部分,即+增加+他们的
> 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