Using cat command in Linux


Gaming Laptop Series

The cat command which is derived from the word concatenate is one of the most frequently used commands in Linux. It reads data from a file and prints it on standard output. It can be used to create, append the content of one file to the end of another file, view the content of a file.

In this article, we will discuss the usage of the cat command with some examples.

Syntax of the cat command

The syntax of the cat command is given below –

cat [option] filename

The options that can be used with the cat command are given in cat command options.

How to display the content of a file using the cat command

Use the cat command without any option to see its content in your terminal. Now use the following command to display the content of a file –

cat file1.txt

You can use this command to view the content of multiple files also –

cat file1.txt file2.txt

Viewing file which contains larger content

If a file has larger content that can’t be displayed at once in your terminal then you should use the cat with less or more commands.

cat file1.txt | less

or

cat file1.txt | more

In this way, you can easily scroll up and down and read the content of a file.

Viewing the content of a file with line number

To view the content of a file with its line number you need to use the option -n with the cat command. Now use –

cat -n file1.txt

How to create a file using the cat command

We can use the cat command to create a new file. You need to use > or >> redirection operators with the cat command now use the following command to create a new file –

cat > newfile.txt

Once this command executes immediately you can start entering text, to save the content of this file and exit you need to press ctrl+d.

How to copy the content of one file to another

You can copy the content of one file to another by using using a redirection operator  > with the cat command. Now to copy the content of file1.txt to file2.txt use the following command in your terminal-

cat file1.txt > file2.txt

If file2.txt already has some content then it will be overwritten and the content file1.txt will be copied to file2.txt.

How to append the content of two files

If you want to append the two files then you need to use >> with the cat command. For example, see the following command –

cat file1.txt >> file2.txt

Instead of overwriting the content of file2.txt, the above command will append the content of file1.txt to the end of file2.txt.

How to sort the content of multiple files and store it in a single file

You can sort the content of multiple files and store it into a different file by using the following command in your terminal –

cat file1.txt file2.txt file3.txt | sort > file4.txt

Conclusion

That’s how you can use the cat command for different tasks. Now if you have a query then leave it in the comments below.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.