ファイルの最初の行に新しいテキスト行を追加するには? [コピー]

ファイルの最初の行に新しいテキスト行を追加するには? [コピー]

文書:

TABLE1

1234 
9555    
87676  
2344

予想出力:

Description of the following table:
TABLE1

1234
9555
87676
2344

答え1

実際に必要なものを実行するのに十分ですechocat

echo "Description of the following table:" | cat - file

このパラメータはから読み込むように-指示します。catstdin

答え2

そしてsed

$ sed -e '1i\
Description of the following table:
' <file
Description of the following table:
TABLE1

1234
9555
87676
2344

答え3

printf "%s\n" 1 i "Description of the following table:" . w | ed filename

コマンド(1行に1つずつ)を出力しますprintfeded filename

ed指示に従ってファイルを編集します。

1                                        # go to line 1
i                                        # enter insert mode
Description of the following table:      # text to insert
.                                        # end insert mode
w                                        # write file to disk

ちなみに、他のほとんどのテキスト編集ツールと同様に、一時ファイルに書き込んで移動するのではなく、真のed内部編集を実行します。sed編集されたファイルはファイルシステムで同じinodeを保持します。

答え4

awk オプションは次のとおりです。

gawk '
      BEGIN{print "Description of the following table:"}
      {print $0}' file > temp && mv temp file

sedにはファイルに直接書き込むことができる内部編集オプション-iがあるので、これはsedよりも少し作業があります。

関連情報