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


89

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


1
重击head -n 100 yourfile.csv > shrunkfile.csv && echo 'morelines' >> shrunkfile.csv
埃里克·莱斯钦斯基

Answers:


147

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

要么:

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

一键完成。

因此,将这两个想法联系在一起,如果您想将input.txt文件的前10行output.txt添加到并添加一行包含五个"="字符的行,则可以使用以下方法:

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

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


21

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

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

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


3
子shell使您无需重新打开输出文件即可执行此操作:(head -n10 file.txt ; echo "Some stuff" ; tail -n +10 file.txt) > newfile.txt
hobbs

5

前几行:man head

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

echo 'This goes at the end of the file' >> file
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.