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