head と tail を使用してさまざまなラインセットをインポートして同じファイルに保存する

head と tail を使用してさまざまなラインセットをインポートして同じファイルに保存する

これは宿題ですが、具体的な宿題の質問はしません。

headとtailを使用してファイルから別の行セットをインポートする必要があります。行6-11と行19-24に似ており、どちらも別のファイルに保存します。私は追加を使用してこれを行うことができることを知っています。

head -11 file|tail -6 > file1; head -24 file| tail -6 >> file1. 

しかし、私たちはそうしてはいけないと思います。
headコマンドとtailコマンドを組み合わせてファイルに保存する特別な方法はありますか?

ベストアンサー1

同様の構造を使用してコマンドをグループ化する場合は、head別の基本操作を使用してこれを実行できます。{ ... ; }

{ head -n ...; head -n ...; ...; } < input_file > output_file

すべてのコマンドは同じ入力を共有します(ありがとう@mikeserv)。
6-11行と19-24行目を取得するには、

head -n 5 >/dev/null  # dump the first 5 lines to `/dev/null` then
head -n 6             # print the next 6 lines (i.e. from 6 to 11) then
head -n 7 >/dev/null  # dump the next 7 lines to `/dev/null` ( from 12 to 18)
head -n 6             # then print the next 6 lines (19 up to 24)

したがって、デフォルトでは次のように実行します。

{ head -n 5 >/dev/null; head -n 6; head -n 7 >/dev/null; head -n 6; } < input_file > output_file

おすすめ記事