Переформатировать большой текстовый файл в однострочные строки (через BASH).

StackOverflow https://stackoverflow.com/questions/1617632

  •  06-07-2019
  •  | 
  •  

Вопрос

Файл1:

hello
- dictionary definitions:
hi
hello
hallo
greetings
salutations
no more hello for you
-
world
- dictionary definitions:
universe
everything
the globe
the biggest tree
planet
cess pool of organic life
-

Мне нужно отформатировать это (для огромного списка слов) в формат определения термина (одна строка на термин).Как этого можно достичь?Ни одно из слов не является одинаковым, только структура, показанная выше.Результирующий файл будет выглядеть примерно так:

hello    - dictionary definitions:    hi    hello    hallo    greetings    salutations    no more hello for you    -
world    - dictionary definitions:    universe    everything    the globe    the biggest tree    planet    cess pool of organic life    -

Awk/Sed/Grep/Cat — обычные соперники.

Это было полезно?

Решение

awk 'BEGIN {FS="\n"; RS="-\n"}{for(i=1;i<=NF;i++) printf("%s   ",$i); if($1)print"-";}' dict.txt

выходы:

hello   - dictionary definitions:   hi   hello   hallo   greetings   salutations   no more hello for you   -
world   - dictionary definitions:   universe   everything   the globe   the biggest tree   planet   cess pool of organic life   -

Другие советы

и кто сказал, что только Perl может сделать это элегантно?:)

$ gawk -vRS="-\n" '{gsub(/\n/," ")}1' file
hello - dictionary definitions: hi hello hallo greetings salutations no more hello for you
world - dictionary definitions: universe everything the globe the biggest tree planet cess pool of organic life

ИЛИ

# gawk 'BEGIN{RS="-\n";FS="\n";OFS=" "}{$1=$1}1'  file
hello - dictionary definitions: hi hello hallo greetings salutations no more hello for you
world - dictionary definitions: universe everything the globe the biggest tree planet cess pool of organic life

Однострочник Perl:

perl -pe 'chomp;s/^-$/\n/;print " "' File1

дает

 hello - dictionary definitions: hi hello hallo greetings salutations no more hello for you
 world - dictionary definitions: universe everything the globe the biggest tree planet cess pool of organic life 

Это «что-то вроде» вашего требуемого результата.

Не уверен, какой язык сценариев вы будете использовать, псевдокод здесь:

for each line
 if line is "-"
  create new line
 else
  append separator to previous line
  append line to previous line
 end if
end for loop

Попробуйте, чтобы этот один лайнер работал при условии, что в слове всегда будет 6 строк.

sed 'N;N;N;N;N;N;N;N;s/\n/ /g' test_3
sed -ne'1{x;d};/^-$/{g;s/\n/ /g;p;n;x;d};H'
awk -v'RS=\n-\n' '{gsub(/\n/," ")}1'
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top