Thursday, December 27, 2012

cat command in Unix/Linux

The cat command is one of the most frequently used command in unix/linux.Many people use it to view the contents of the file or to concatenate two files.However,there is much more you can do with this command 


 Displaying the contents of a file

The most basic use for the cat command is to display the contents of a file.The syntax is
cat filename(or filepath)

The above command will display the contents of the file on screen.





Concatenating multiple files

The cat command can also concatenate the contents of multiple files.This does not affect the original file(s).In this example,cat will concatenate the contents of three files demo_file,demo_file1 and demo_file2 and the result will be redirected to a new file named test.



















Create a file

cat can also create a text file.To create a file test.txt use this command
cat > test.txt
You can then whatever you want.To save the file and exit use CTRL+D








Copy a file

The cat command can also be used to create a new file and transfer to it the data from an existing file.
cat oldfile > newfile

To output file1's contents, then standard input, then file2's contents,use

cat file1 - file2

To see the effect of the above command we redirect the output of the above command to a new file
cat file1 -file2 >foo1.txt

Enter some text(standard input) and then use CTRL+D to save and exit.Catting the file will show you the result.

A hyphen indicates that input is taken from the keyboard. In this example, to create a new file file2 that consists of text typed in from the keyboard followed by the contents of file1, enter: 
cat - file1 > file2


Some useful options

To number non-blank output lines use -b option
cat -b filename

To number all output lines use -n option
cat -n filename

To squeeze multiple adjacent blank lines use -s option
cat -s filename





No comments: