Thursday 8 August 2019

12 CAT COMMAND EXAMPLES IN LINUX/UNIX

Cat(concatenate) command is an excellent command used to view files. This will conCATenate(Combines two are more files) and display it’s 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 .
Example 1: Display file content on stranded output (STDOUT)
cat filename.txt
or
cat < filename.txt
Example 2: Send the file content as input to other command. For example count number of lines in a file
cat filename.txt | wc -l
Example 3: 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)
Example 4: 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

Example 5:
 Copy one file content to other (don’t overwrite but append it)
cat file1.txt >> file2.txt
Example 6: 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 
Example 7: Copy 2 files in to third file(append the date to third file)
cat file1.txt file2.txt >> file3.txt
Example  8: 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.
Example 9: Display the file content along with number of the line or number the line numbers using cat command
cat -n filename.txt
Example 10: Display file content along with numbers for lines with data
cat -b filename.txt
Example 11: 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 12: 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