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?
You need to use the >> to append text to end of file. It is also useful to redirect and append/add line to end of file on Linux or Unix-like system.
To look at the first few lines of a file, type head filename, where filename is the name of the file you want to look at, and then press <Enter>. By default, head shows you the first 10 lines of a file. You can change this by typing head -number filename, where number is the number of lines you want to see.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With