大きなテキストファイルを1行の文字列に再フォーマットする(BASH経由)
質問
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
-
これは(膨大な単語のリストのために)用語から定義へのフォーマット(用語ごとに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 -
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 one-liner:
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
この1つのライナーは、単語が常に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'
所属していません StackOverflow