Pages

Tuesday, August 21, 2012

20+ Linux/Unix cat command examples

Cat command is an excellent command used to view files. This will conCATenate(Combines two are more files) and display its content on the screen. Cat command not only display the file content but it can also do merging files , creating files sending one file to other file etc. Lets learn cat command with with practical examples first and then with  some  options .

Example1: Display file content on stranded output (STDOUT)

cat filename.txt

or
cat < filename.txt

Example2: Send the file content as input to other command. For example count number of lines in a file

cat filename.txt | wc -l

Example3: Create a file using cat. execute below command start typing the contents on the screen/at terminal once you enter your data, save the file by pressing ctrl+d

cat > filename.txt

asdfasd
a
sdf

sadfsad
fasd
asdf
asdf
(press ctrl+d)

Example4: Copy one file content to other(over write the file)

cate file1.txt > file2.txt

<, >, | operators etc are called as redirect operators here redirect operators with examples

Example5:
Copy one file content to other(dont overwrite but append it)

cat file1.txt >> file2.txt

Example6: Copy 2 files in to third file(overwrite if the third file exists)

cat file1.txt file2.txt > file3.txt


or

cat file{1,2}.txt > file3.txt

learn more about {} braces 

Example7: Copy 2 files in to third file(append the date to third file)

cat file1.txt file2.txt >> file3.txt

Example8: To copy file abc.txt and write some date using keyboard then redirecting both to a file called xyz.txt

cat - abc.txt > xyz.txt

cat abc.txt - > xyz.txt

Note: The first command will write keyboard typed date first to file xyz.txt then abc.txt to xyz.txt. Where as the command first abc.txt data is written to xyz.txt then followed with the data entered from keyboard.


Example8: Display the file content along with number of the line or number the line numbers using cat command

cat -n filename.txt

Example9: Display file content along with numbers for lines with data

cat -b filename.txt

Example10: Hide repeated empty lines when displaying content of the file.

cat -s filename.txt

Note: This command will display single empty line for a sequence of multiple empty lines.

Example: Display tabs in a file using cat command

cat -t filename.txt

There are many more cat command options which we can get through manual pages.

whatis cat

or

man cat

or

info cat

0 comments:

Post a Comment