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

Linux Problem Overview


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 Solutions


Solution 1 - Linux

The head command can get the first n lines. Variations are:

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.

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.txt file to output.txt and append a line with five "=" characters, you could use something like:

( 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.

Solution 2 - Linux

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.

Solution 3 - Linux

First few lines: man head.

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

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

Solution 4 - Linux

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionbiznezView Question on Stackoverflow
Solution 1 - LinuxpaxdiabloView Answer on Stackoverflow
Solution 2 - LinuxDJ.View Answer on Stackoverflow
Solution 3 - LinuxstragerView Answer on Stackoverflow
Solution 4 - LinuxAmit JainView Answer on Stackoverflow