Riformatta un file di testo di grandi dimensioni in stringhe di una riga (tramite BASH)
Domanda
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
-
Devo formattare questo (per un enorme elenco di parole) in un termine in formato di definizione (una riga per termine). Come si può ottenere questo? Nessuna delle parole è la stessa, solo la struttura vista sopra è. Il file risultante sarebbe simile al seguente:
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 sono i soliti contendenti.
Soluzione
awk 'BEGIN {FS="\n"; RS="-\n"}{for(i=1;i<=NF;i++) printf("%s ",$i); if($1)print"-";}' dict.txt
uscite:
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 -
Altri suggerimenti
e chi dice che solo Perl può farlo elegantemente? :)
$ 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
o
# 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
Un perl one-liner:
perl -pe 'chomp;s/^-$/\n/;print " "' File1
dà
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
Questo è "qualcosa come" l'output richiesto.
Non sei sicuro del linguaggio di script che userai, pseudo codice qui:
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
Prova questo one liner a condizioni che il tuo sarà sempre 6 righe per una parola
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'
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow