Thursday, October 17, 2013

UNIX: cat Command

cat command

Cat command is one of the basic UNIX command.
cat displays a file content. What more could this command do?
here is 5 practical usage examples for cat command.

1. Display the contents of a file

When you pass the filename as an argument to cat, it displays the contents of the file as shown below.

$ cat myfile.txt
 
This is the first line in myfile
 
You can also display contents of more than one file as shown below.

$ cat myfile.txt yourfile.txt
 
This is the first line in myfile
 
This is the first line in your file

2. Create a New File

cat command receives input from stdin and redirected to the screen

$ cat
cat command for file oriented operations.
cat command for file oriented operations.
cp command for copy files or directories.
cp command for copy files or directories.
 

The lines received from stdin can be redirected to a new file using redirection symbol.

$ cat >mynewfile.txt
 
this is new file


*press Ctrl+D to save and exit 
 

To append some content to a file, use >> redirection symbol as shown below.

$ cat >> myfile.txt
This is the second line in myfile
*press Ctrl+D to save and exit 
this will add a new line to the end of myfile.txt

3. Copy File Content

Redirection symbols in unix plays an important role in processing the standard file descriptor contents. Using it, you can copy the contents of one file into another as shown below.

$ cat myfile.txt >ourfile.txt

As seen above, since we used the output redirection, the content 
displayed in standard output gets directed into a new file called 
ourfile.txt

4. Concatenate Contents of Multiple Files

Through cat command, you will be able to concatenate contents of more than one file into a new file.
For example, the text from myfile.txt and youfile.txt gets combined into a new file ourfile.txt


$ cat myfile.txt yourfile.txt >ourfile.txt

As seen above, stdout gets redirected and the new file has been 
created with the contents of myfile.txt and yourfile.txt

5. Display Line numbers

To display the contents of a file with the line number in front of each line, use option -n.
$ cat -n ourfile.txt
1 This is the first line in myfile
2 This is the second line in myfile
3 This is the first line in your file
In case of numbering only nonempty lines, use option -b as follows,

$ cat -b ourfile.txt
Note that the lines which contains whitespaces are not considered as empty lines and the same applicable to line numbered 2.

No comments:

Post a Comment