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

biz*_*nez 82 linux

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

pax*_*blo 131

head命令可以获得第一n行.变化是:

head -7 file
head -n 7 file
head -7l file
Run Code Online (Sandbox Code Playgroud)

这将获得调用文件的前7行"file".要使用的命令取决于您的版本head.Linux将与第一个一起使用.

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

echo 'first line to add' >>file
echo 'second line to add' >>file
echo 'third line to add' >>file
Run Code Online (Sandbox Code Playgroud)

要么:

echo 'first line to add
second line to add
third line to add' >>file
Run Code Online (Sandbox Code Playgroud)

一击就做.

所以,将这两个想法结合在一起,如果你想得到input.txt文件的前10行output.txt并附加一个包含5个"="字符的行,你可以使用类似的东西:

( head -10 input.txt ; echo '=====' ) > output.txt
Run Code Online (Sandbox Code Playgroud)

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


DJ.*_*DJ. 17

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

head -n10 file.txt >> newfile.txt
echo "your line >> newfile.txt
tail -n +10 file.txt >> newfile.txt
Run Code Online (Sandbox Code Playgroud)

如果您不想从文件中留下其余的行,只需跳过尾部即可.

  • 子shell允许你这样做而不重新打开输出文件:`(head -n10 file.txt; echo"some stuff"; tail -n +10 file.txt)> newfile.txt` (3认同)

str*_*ger 5

前几行:man head.

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

echo 'This goes at the end of the file' >> file
Run Code Online (Sandbox Code Playgroud)