附加到大文件的顶部:bash

Ste*_*lis 12 bash grep append

我有一个近3 GB的文件,我想在顶部添加两行.每次我尝试手动添加这些行时,vim和vi都会冻结保存(我让他们尝试每次保存大约10分钟).我希望有一种方法可以附加到顶部,就像你附加到文件底部一样.到目前为止我唯一看到的东西包括一个临时文件,我觉得由于文件大小会很慢.我希望有类似的东西:

grep -top lineIwant >> fileIwant
Run Code Online (Sandbox Code Playgroud)

有谁知道附加到文件顶部的好方法?

Fre*_*ihl 13

尝试

cat file_with_new_lines file > newfile
Run Code Online (Sandbox Code Playgroud)


spe*_*akr 7

我做了一些基准比较,使用sed与就地编辑(如此处所示)和cat(如此处所示)进行比较.

~3GB bigfile填充点:

$ head -n3 bigfile
................................................................................
................................................................................
................................................................................

$ du -b bigfile
3025635308      bigfile
Run Code Online (Sandbox Code Playgroud)

使用两行文件换行符插入bigfile之上:

$ cat newlines
some data
some other data

$ du -b newlines
26      newlines
Run Code Online (Sandbox Code Playgroud)

使用dumbbench v0.08的基准测试结果:

:

$ dumbbench -- sh -c "cat newlines bigfile > bigfile.new"
cmd: Ran 21 iterations (0 outliers).
cmd: Rounded run time per iteration: 2.2107e+01 +/- 5.9e-02 (0.3%)
Run Code Online (Sandbox Code Playgroud)

sed重定向:

$ dumbbench -- sh -c "sed '1i some data\nsome other data' bigfile > bigfile.new"
cmd: Ran 23 iterations (3 outliers).
cmd: Rounded run time per iteration: 2.4714e+01 +/- 5.3e-02 (0.2%)
Run Code Online (Sandbox Code Playgroud)

使用就地编辑进行sed:

$ dumbbench -- sh -c "sed -i '1i some data\nsome other data' bigfile"
cmd: Ran 27 iterations (7 outliers).
cmd: Rounded run time per iteration: 4.464e+01 +/- 1.9e-01 (0.4%)
Run Code Online (Sandbox Code Playgroud)

因此,在对大文件进行就地编辑时,sed似乎更慢(80.6%),这可能是由于之后将中间临时文件移动到原始文件的位置.使用I/O重定向sed仅比cat慢11.8%.

根据这些结果,我会按照答案中的建议使用cat.