Sunday, 5 February 2017

Cat Command

Cat Command:

                cat is one of the most frequently used commands on Unix-like operating systems. It has three related functions with regard to text files:
            
            1. Displaying files
2. Combining copies of files
3. Creating new files.

Displaying Files

                To display a file

Syntax:

cat file_name
               
  If the file is too large for all of the text to fit on the monitor screen simultaneously, as is frequently the case, the text will scroll down the screen at high speed and be very difficult to read. This problem is easily solved by piping the output to the filter less, i.e.,

       cat file1 | less
              
  As well we can try with more command for this like below
    
           Cat file1 | more

Combining copies of files

                    The second role of cat is concatenation (i.e., stringing together) of copies of the contents of files. (This is the source of cat's curious name.) Because the concatenation occurs only to the copies, there is no effect on the original files.

For example, the following command will concatenate copies of the contents of the three files file1, file2 and file3:

cat file1 file2 file3

The contents of each file will be displayed on the monitor screen (which, again, is standard output, and thus the destination of the output in the absence of redirection) starting on a new line and in the order that the file names appear in the command. This output could just as easily be redirected using the output redirection operator to another file, such as file4, using the following:

cat file1 file2 file3 > file4


In the next example, the output of cat is piped to the sort filter in order to alphabetize the lines of text after concatenation and prior to writing to file4:

           cat file1 file2 file3 | sort > file4

File Creation

            The third use for cat is file creation. For small files this is often easier than using vi, gedit or other text editors. It is accomplished by typing cat followed by the output redirection operator and the name of the file to be created, then pressing ENTER and finally simultaneously pressing the CONTROL and d keys. For example, a new file named file1 can be created by typing

cat > file1

Then pressing the ENTER key and finally simultaneously pressing the CONTROL and d keys.

If a file named file1 already exists, it will be overwritten (i.e., all of its contents will be erased) by the new, empty file with the same name. Thus the cautious user might prefer to instead use the append operator (represented by two successive rightward pointing angular brackets) in order to prevent unintended erasure. That is,

cat >> file1

To create a new file file2 that consists of the contents of file2 followed by text typed in from the keyboard, first enter the following:


cat file1- > file2

No comments:

Post a Comment