Объединить несколько строк, которые имеют одинаковый шаблон запуска - PullRequest
0 голосов
/ 12 декабря 2018

У меня есть текстовый файл со следующим содержимым.

-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 голосов
/ 12 декабря 2018

Это еще один 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}'
0 голосов
/ 12 декабря 2018

Использование 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
0 голосов
/ 12 декабря 2018

Вы можете использовать это 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

-country -the -elections
+countries +be +a +chance
-the -means -we
+need +people’s +choice
-democracy
+democracies
-elections -there
+increases +their
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...