
各行の先頭に置かれた任意の「タグ」に基づいて複数のファイルに分割したいテキストファイルがいくつかあります。
テキストファイルの例:
I CELEBRATE myself, and sing myself,
And what I assume you shall assume,
For every atom belonging to me as good belongs to you.
#here I loafe and invite my soul,
#here I lean and loafe at my ease observing a spear of summer grass.
#there My tongue, every atom of my blood, form'd from this soil, this air,
#there Born here of parents born here from parents the same, and their parents the same,
#here I, now thirty-seven years old in perfect health begin,
#here Hoping to cease not till death.
この例では、で始まるすべての行を削除し、という名前のファイルに追加し、で始まるすべての行を名前のファイルに#here
追加し、表示されていないすべての行を元のファイルに保存しようとしています。 (このプロセスでタグを削除するのが最善です。)here.txt
#there
there.txt
#here
#there
以下を使用するこのソリューションが役に立つと思いますawk
が、私はUnix初心者ユーザーであり、それを私の問題に適用する方法がわかりません。キーワード境界を使用してファイルを分割する方法
進行方法の提案がありますか?
PS:私はOS Xでコマンドラインを使用しています。
答え1
あなたのケースはリンクされたケースよりも簡単です。各行を見て(またはawk用語で「記録」)、どこに送信するかを決定します。だから:
awk '/^#here/{print > "here.txt"; next} /^#there/{print > "there.txt"; next} {print}' input.txt
残りの行は標準出力として印刷されます。移植可能であれば、それを3番目のファイル(rest.txt
例:)にリダイレクトしてから、名前を元のファイル名に変更できます。 GNU awkがある場合は、このinplace
モジュールを使用して元のファイルを直接変更できます。
gawk -i inplace '/^#here/{print > "here.txt"; next} /^#there/{print > "there.txt"; next} {print}' input.txt
答え2
使用sed
w
コマンド:
sed -n -e '/^#here/w here.txt' -e '/^#there/w there.txt' data
目的のパターンで始まらない行を維持するには、次の手順を実行します。
sed -n -e '/^#here/w here.txt' -e '/^#there/w there.txt' -e '/^$/d;' -e '/^#/!w new_data.txt' data
これにより、sed
一致がその行に適用され、そのファイルに書き込まれます。
行が表示されず/^#/!
()空でない場合(/^$/
)その行は、表示されていないすべての行を含む名前のファイルに書き込まれますnew_data.txt
。
空白行を維持するには、-e /^$/d;
コマンドラインから削除してください。