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

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

156161 次浏览

前几行: man head

追加行: 在 Bash 中使用 >>操作符(?) :

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

head命令可以得到第一个 n行:

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

它将获得文件的前7行,称为 "file"。要使用的命令取决于 head的版本。Linux 将与第一个一起工作。

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

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

一击必中。

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

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

在本例中,我们在一个子 shell 中执行这两个操作,以便将输出流合并为一个,然后使用该流创建或覆盖输出文件。

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

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

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

sed -n '1,10p' filename > newfile
echo 'This goes at the end of the file' >> newfile