23

私は巨大なcsvファイル(テラバイトのオーダー)を持っています。

ここで、ヘッダーである1つの行を一番上に挿入します。

たとえば、input.csvが次のようになっている場合:

 1,2,3,4
 22,3,23,1

私はそれを次のように見せたい

id1,id2,id3,id4
 1,2,3,4
 and so on

シェル、ターミナル、awk、bashからこれを行うにはどうすればよいですか?/

4

5 に答える 5

38

代わりに、sedを使用します。

sed -i 1i"id1,id2,id3,id4" file.csv

編集:

@Ed Mortonが指摘しているように、-iスイッチsedでsedを使用すると、ファイルが所定の位置で編集されるため、大きなファイルを編集するときに危険な場合があります。オプションの後にプレフィックスを指定すると-i、sedはバックアップを作成します。したがって、このようなものの方が安全です。

sed -i.bak 1i"id1,id2,id3,id4" file.csv

元のファイルは次の場所に配置されますfile.csv.bak

于 2012-11-15T17:33:12.753 に答える
17

これはとても簡単です:

{ echo "id1,id2,id3,id4"; cat file.csv; } > newfile.csv

単純なシェル連結を使用します。

編集

以下のディスカッションスレッドの後、私はこれを提案します:

  • ヘッダー付きのファイルを作成すると、head.txt

それで :

cat head.txt file.csv > newfile.csv
于 2012-11-15T17:20:23.063 に答える
3

Edit. When I wrote this answer, I overlooked the "terabyte" part of the question. Hence, do not use the method presented here. I still leave this post, as it advertises the use of this wonderful tool, ed, the standard text editor.

As usual, ed is the standard text editor. The solution using sed -i doesn't, as it mentions, "edit the file in place". Instead, it outputs its content to a temporary file, and then renames this file to the original one. That's really not good for large files!

Using ed instead really edits the file. Something along the following lines:

#!/bin/bash

file="input.csv"

{
ed -s "$file" <<EOF
1
i
id1,id2,id3,id4
.
wq
EOF
} > /dev/null

Explanation: 1 goes to the first line, i goes into insert mode, then we insert id1,id2,id3,id4 then . to go back to normal mode, and wq to write and quit.

With this method, you're really editing the file and it's twice faster than the sed method. Also, ed is known to be "large file safe"!

Done.

于 2012-11-15T18:45:48.230 に答える
1

簡単な方法はありません。ファイルを書き直す必要があります。おそらく最も安全な方法は

 ( echo "id1,id2,id3,id4" ; cat file ) > newFile && rm file

IHTH

于 2012-11-15T17:21:00.113 に答える
-2

echo "id1、id2、id3、id4" >> data.csv

于 2021-03-03T06:13:10.850 に答える