Как разобрать мультилинию с awk без странных дубликатов - PullRequest
2 голосов
/ 11 июля 2019

Я пытаюсь разобрать вывод pacman -Qi, это выглядит примерно так:

Name            : zvbi
Version         : 0.2.35-3
Description     : VBI capture and decoding library
Build Date      : Fri 24 Aug 2018 09:48:59 CEST
Install Date    : Thu 30 Aug 2018 08:55:50 CEST
Install Reason  : Installed as a dependency for another package
Install Script  : No
Validated By    : Signature

Name            : zziplib
Version         : 0.13.69-1
Description     : A lightweight library that offers the ability to easily extract data from files archived in a single zip file
Build Date      : Wed 21 Mar 2018 21:16:20 CET
Install Date    : Thu 22 Mar 2018 11:13:19 CET
Install Reason  : Installed as a dependency for another package
Install Script  : No
Validated By    : Signature

Мне нужно разобраться в этом:

zvbi    VBI capture and decoding library
zziplib    A lightweight library that offers the ability to easily extract data from files archived in a single zip file

Пробелы являются символами табуляции

Прямо сейчас я попытался разобрать это: pacman -Qi | awk -F: '/^Name/ {n=$2} /^Desc/ {d=$2} {print n "\t" d}'

Но выводит это

 zvbi   
 zvbi   
 zvbi    VBI capture and decoding library
 zvbi    VBI capture and decoding library
 zvbi    VBI capture and decoding library
 zvbi    VBI capture and decoding library
 zvbi    VBI capture and decoding library
 zvbi    VBI capture and decoding library
 zvbi    VBI capture and decoding library
 zvbi    VBI capture and decoding library
 zvbi    VBI capture and decoding library
 zvbi    VBI capture and decoding library
 zvbi    VBI capture and decoding library
 zvbi    VBI capture and decoding library
 zvbi    VBI capture and decoding library
 zvbi    VBI capture and decoding library
 zvbi    VBI capture and decoding library
 zvbi    VBI capture and decoding library
 zvbi    VBI capture and decoding library
 zvbi    VBI capture and decoding library
 zvbi    VBI capture and decoding library
 zvbi    VBI capture and decoding library
 zziplib     VBI capture and decoding library
 zziplib     VBI capture and decoding library
 zziplib     A lightweight library that offers the ability to easily extract data from files archived in a single zip file
 zziplib     A lightweight library that offers the ability to easily extract data from files archived in a single zip file
 zziplib     A lightweight library that offers the ability to easily extract data from files archived in a single zip file
 zziplib     A lightweight library that offers the ability to easily extract data from files archived in a single zip file
 zziplib     A lightweight library that offers the ability to easily extract data from files archived in a single zip file
 zziplib     A lightweight library that offers the ability to easily extract data from files archived in a single zip file
 zziplib     A lightweight library that offers the ability to easily extract data from files archived in a single zip file
 zziplib     A lightweight library that offers the ability to easily extract data from files archived in a single zip file
 zziplib     A lightweight library that offers the ability to easily extract data from files archived in a single zip file
 zziplib     A lightweight library that offers the ability to easily extract data from files archived in a single zip file
 zziplib     A lightweight library that offers the ability to easily extract data from files archived in a single zip file
 zziplib     A lightweight library that offers the ability to easily extract data from files archived in a single zip file
 zziplib     A lightweight library that offers the ability to easily extract data from files archived in a single zip file
 zziplib     A lightweight library that offers the ability to easily extract data from files archived in a single zip file
 zziplib     A lightweight library that offers the ability to easily extract data from files archived in a single zip file
 zziplib     A lightweight library that offers the ability to easily extract data from files archived in a single zip file
 zziplib     A lightweight library that offers the ability to easily extract data from files archived in a single zip file
 zziplib     A lightweight library that offers the ability to easily extract data from files archived in a single zip file
 zziplib     A lightweight library that offers the ability to easily extract data from files archived in a single zip file
 zziplib     A lightweight library that offers the ability to easily extract data from files archived in a single zip file

И использование uniq дает это

 zvbi   
 zvbi    VBI capture and decoding library
 zziplib     VBI capture and decoding library
 zziplib     A lightweight library that offers the ability to easily extract data from files archived in a single zip file

Обратите внимание на пробел в начале каждой строки.

Я думаю, что это можно сделать, проверив состояние переменных n и d, напечатав их, когда они оба установлены, затем очистив их, но я не уверен, как это сделать.

Ответы [ 3 ]

2 голосов
/ 11 июля 2019

Не могли бы вы попробовать следующее.

awk '
BEGIN{
  OFS="\t"
}
/^Name/{
  if(value){
     print value
  }
  sub(/.*: /,"")
  value=$0
  next
}
/^Description/{
  sub(/.*: /,"")
  value=(value?value OFS:"")$0
}
END{
  if(value){
    print value
  }
}
'  Input_file
1 голос
/ 11 июля 2019

Вы были близки:

$ awk -F': ' '/^Name/ {n=$2} /^Desc/ {print n "\t" $2}' file
zvbi    VBI capture and decoding library
zziplib A lightweight library that offers the ability to easily extract data from files archived in a single zip file

Основная проблема с вашим сценарием заключалась в том, что блок {print...} выполнялся для каждой строки ввода, а не только когда была замечена строка Desc, и тогда вы не включали пробел после : в Ваш FS, так что он все еще присутствовал в каждом поле.

0 голосов
/ 11 июля 2019

И я написал написанный сценарий sed:

pacman -Qi | sed -n '/^\(Name\|Description\)[[:space:]]*: /{s///;H}; /^$/ba; $ba; d; :a;x;s/^\n//;s/\n/\t/;p'
  1. /^\(Name\|Description\)[[:space:]]*: /{s///;H}; /^$/ba - каждая строка, начинающаяся с Name и Description, удаляет macthed-часть и добавляется кудерживать пространство.
  2. /^$/ba; $ba; d; - Если встречается пустая строка или конец файла, мы разветвляемся, чтобы пометить a;В противном случае мы начинаем новый цикл.
  3. :a;x;s/^\n//;s/\n/\t/;p - В метке a мы обмениваемся пробелом с пробелом, удаляем начальную новую строку (не знаю, откуда она), подставляем первую новую строку с вкладкой и печатаем вывод.

Пример вывода:

zlib    Compression library implementing the deflate compression method found in gzip and PKZIP
zsh A very advanced and programmable command interpreter (shell) for UNIX
zstd    Zstandard - Fast real-time compression algorithm
zvbi    VBI capture and decoding library
zziplib A lightweight library that offers the ability to easily extract data from files archived in a single zip file
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...