Copying Part of a File

Question: What command or sequence of commands can you use to copy the first three lines of one file to another?
anonymous

Answer: You can do this very simply using just one command. The command has several parts and I'll explain it one part at a time so you know what each part of the command does.

The head command by default displays the first 20 lines of a file on the screen. If you enter the command head fred then the first 20 lines in the file called fred will be displayed.

We can add a parameter to this to change the number of lines displayed. head -3 fred will display only the first three lines.

The next thing that we need to do is to redirect the output so that instead of displaying the output on the screen we instead write it to a file. Here we have two options, we can either replace the file or we can append to the existing file. To redirect output from a command and replace the contents of an existing file (or create the file if it doesn't exist) we use the > operator. If instead we want to append to the existing file rather than overwrite it we use the >> operator. So if we want to append the first three lines of a file called fred to the end of a file called john we would use the command
head -3 fred >> john or if we wanted to overwrite the file instead we'd only use one greater than.

 

This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow
Donate