如何复制一个巨型文件的前几行,并使用一些 Linux 命令在它的末尾添加一行文本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1325701/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 17:38:27  来源:igfitidea点击:

How to copy the first few lines of a giant file, and add a line of text at the end of it using some Linux commands?

linux

提问by biznez

How do I copy the first few lines of a giant file and add a line of text at the end of it, using some Linux commands?

如何使用一些 Linux 命令复制巨型文件的前几行并在其末尾添加一行文本?

采纳答案by paxdiablo

The headcommand can get the first nlines. Variations are:

head命令可以获得第一n行。变化有:

head -7 file
head -n 7 file
head -7l file

which will get the first 7 lines of the file called "file". The command to use depends on your version of head. Linux will work with the first one.

这将获得名为"file". 要使用的命令取决于您的head. Linux 将使用第一个。

To append lines to the end of the same file, use:

要将行附加到同一文件的末尾,请使用:

echo 'first line to add' >>file
echo 'second line to add' >>file
echo 'third line to add' >>file

or:

或者:

echo 'first line to add
second line to add
third line to add' >>file

to do it in one hit.

一击即可完成。

So, tying these two ideas together, if you wanted to get the first 10 lines of the input.txtfile to output.txtand append a line with five "="characters, you could use something like:

因此,这两种想法绑在一起,如果你想获得前10行的input.txt文件,output.txt并附加线有五个"="字符,你可以使用这样的:

( head -10 input.txt ; echo '=====' ) > output.txt

In this case, we do both operations in a sub-shell so as to consolidate the output streams into one, which is then used to create or overwrite the output file.

在这种情况下,我们在一个子 shell 中执行这两个操作,以便将输出流合并为一个,然后用于创建或覆盖输出文件。

回答by strager

First few lines: man head.

前几行:man head.

Append lines: use the >>operator (?) in Bash:

附加行:>>在 Bash 中使用运算符 (?):

echo 'This goes at the end of the file' >> file

回答by DJ.

I am assuming what you are trying to achieve is to insert a line after the first few lines of of a textfile.

我假设您要实现的是在文本文件的前几行之后插入一行。

head -n10 file.txt >> newfile.txt
echo "your line >> newfile.txt
tail -n +10 file.txt >> newfile.txt

If you don't want to rest of the lines from the file, just skip the tail part.

如果您不想保留文件中的其余行,只需跳过尾部部分。