Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

Tags:

linux

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?

like image 290
biznez Avatar asked Aug 25 '09 02:08

biznez


People also ask

How do I add a line to the end of a file in Linux?

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.

How do you cat first few lines of a file?

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.


2 Answers

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.

like image 43
DJ. Avatar answered Sep 23 '22 04:09

DJ.


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.

like image 77
paxdiablo Avatar answered Sep 20 '22 04:09

paxdiablo