How to use the linux cat and tac commands

Cat command is a well known Unix utility that reads files sequentially. Writing them to conventional output. The name is derived from its function for concatenating and listing the documents. Tac (that is “cat” backwards) concatenates every record to traditional output much like the cat command. However in opposite: line-by means of-line, printing the last line first. This article explains about “How to use ‘cat’ and ‘tac’ commands with examples”.

The basic example of cat command should be like this –

The above command is to read files and display them to stdout, meaning to display the content of files on your terminal. The sample output should be like this –

Another usage of the cat command is to study or combine a couple of files together and ship the output to a monitor as shown below –

The sample output should be like this –

This command can also be used to concatenate (join) multiple files into one single file using the “>” Linux as shown below –

The above command joins text.txt and text2.txt and concatenates the data into a different file- text3.txt file. The sample output should be like this –

The cat command is also used to copy the content from one file to an other new file. The new (updated) file can be renamed as arbitrary.

For example, copy the following file from the current location to /tmp/ directory as shown below –

The above command copies text.txt file data to file.txt file. The sample output should be like this –

A less usage of the cat command is to create a new file with the below command –

The sample output should be like this –

Usage of Tac Command in Linux

Tac is almost the reverse model of cat command (additionally spelled backwards) which prints every line of a report beginning from the lowest line and completing on the top line in your gadget trendy output. Sample example should be like this –

The sample output should be like this –

The most important usage of tac command is that, it can provide great help in order to debug log files, even reversing the chronological order of log contents.

The sample example should be like this –

The sample output should be like this –

After this article, you will be able to understand – How to Use ‘cat’ and ‘tac’ Commands with Examples in Linux, we will come up with more Linux based tricks and tips. Keep reading!

Cat command is used to read and print file content on a terminal screen. If you bifurcate concatenation, you will get a cat in between, which means you can combine multiple files at once. The cat command is not limited to reading files, and it can do more, let me show you how to leverage cat.

Create a new file using cat

Why use any text editor to write simple text content when you can use cat command with redirection symbol to make a new file content.

Open your terminal screen and pass the following command, and once you give the command, it will ask you to enter a file content.

  • >:- Redirection symbol.
  • [FILE-NAME]:– Provide a file name to save it, if the file exists data will get override.

If you do not wish to enter more content, press Ctrl + D to save it.

The problem with > redirection will erase previous content to save a newer one. To prevent it, use >> redirection; see the below example for a clear view.

Read file content using cat

Above we have created a new file, but how to read it, It’s pretty simple, not much fuss, pass the file name along with cat command.

How to use the linux cat and tac commands

Read multiple file at once using cat

I have heard that the cat command can read multiple files simultaneously rather than opening individual files one by one. Technically that process is called concatenation.

I have created three groups for demo purposes that hold dummy data. Now you will see how to display concatenate data.

How to use the linux cat and tac commands

Redirect cat output to new file

On top, you have seen how to concatenate multiple text files, but what of use when we cannot save for later use. In Linux, everything is possible.

This task can be achieved using redirection symbols. Let me show you how to do.

How to use the linux cat and tac commands

The problem with > the redirection will erase a previous content to save a newer one. To prevent its use >> redirection, see the below example for a clear view.

How to use the linux cat and tac commands

Create number line using cat

This feature is quite helpful to generate number lines or count numbers, even its count blank whitespaces.

To test this, pass the below command with the -n parameter to create numbers.

How to use the linux cat and tac commands

What is tac command?

A tac command is similar to a cat command, but the difference is data will get printed in reverse order. tac command is capable of concatenate, regex and separator.

tac command syntax

Read file in reverse order

I use the tac over tail command for the short files. Let me show you how it works.

How to use the linux cat and tac commands

Seprate the content

This is quite useful for separating content you don’t want to display. Previously I have created multiple files. From that, I don’t want to have group2 data.

To perform this, pass the below command with -s which stand for separator.

How to use the linux cat and tac commands

Difference between cat & tac

The significant difference between cat and tac is cat command can read in up & down manner, and tac read in reverse order apart from that cat can generate number line, read unprintable character, a blank line which all is missing in tac command, however, tac command has the support of regex, separator which can be helpful in bash scripting.

You cannot compare both based on reading ability. Both are developed for different use, a cat is abused much, and tac is suspense for many users.

Wrap-up

I have tried to cover all cat & tac command options, which we can use regularly. I have left tac command with regex, which is out of the scope of this article.

Are you guys interested in how we can use regex in tac command? Please let me know in the comment section.

A man with a tech effusive, who has explored some of the amazing technology stuff and exploring more, While moving towards, I had a chance to work on Android Development, Linux, AWS, DevOps with several Open source tools.
One of my life mottos “Always be lifelong Students.”

How to Use ‘cat’ and ‘tac’ Commands with Examples in Linux?

Cat command, the acronym for Concatenate, is one of the most used commands in *nix systems. The most basic usage of the command is to read files and display them to stdout, meaning to display the content of files on your terminal.

Another usage of the cat command is to read or combine multiple files together and send the output to a monitor as illustrated in the below examples.

The command can also be used to concatenate (join) multiple files into one single file using the “>” Linux redirection operator.

By using the append redirector you can add the content of a new file to the bottom of the file-all.txt with the following syntax.

The cat command can be used to copy the content of file to a new file. The new file can be renamed arbitrary. For example, copy the file from the current location to /tmp/ directory.

Copy the file from the current location to /tmp/ directory and change its name.

A less usage of the cat command is to create a new file with the below syntax. When finished editing the file hit CTRL+D to save and exit the new file.

In order to number all output lines of a file, including empty lines, use the -n switch.

To display only the number of each non-empty line use the -b switch.

Learn How to Use Tac Command in Linux

On the other hand, a lesser known and less used command in *nix systems is tac command. Tac is practically the reverse version of cat command (also spelled backwards) which prints each line of a file starting from the bottom line and finishing on the top line to your machine standard output.

One of the most important option of the command is represented by the -s switch, which separates the contents of the file based on a string or a keyword from the file.

Next, most important usage of tac command is, that it can provide a great help in order to debug log files, reversing the chronological order of log contents.

Disclosure: This post may contain affiliate links, which means we may receive a commission if you click a link and purchase something that we recommended.

How to use the linux cat and tac commands

How to Use Cat, Tac, More, Less – Linux Commands. These basic commands are most effective when used in the correct way. These commands are used on a daily basis for every Linux DevOPS.

In this guide you are going to learn how to use these simple linux commands with examples.

CAT Command

Cat command is a short form for Concatenate, which is one of the most used Linux commands.

Output Contents

This command reads the file and outputs all content to your terminal. The basic syntax in shown below.

Output Contents of Multiple Files

You can also use this command to output all contents of multiple files.

Merge Multiple Files to Single File

You can also merge the contents of all files to a single file using the > operator.

Append to Existing File

You can also append the content of a file to an existing file.

Other Options for CAT Linux Command

There are also other options for CAT command, some of them are listed below.

  • -n: Display the content including the empty lines.
  • -b: Display numbered output of non-empty lines.

TAC Command

Tac command is an exact reversal of cat command. This Linux command is mainly useful to output the latest content of a file starting from the bottom line to the first line.

MORE Command

more command is one of the oldest Linux command which is mainly used to output the content of the file page by page. If your file is too big you can use the more command to output the contents.

You can use the – operator to tell the command to output n number of lines in a page.

You can use the + operator to tell the command to start output the content from a specific line.

LESS Command

The less command is one of the flexible Linux command which is similar to more command but have more advantages. This command outputs the content in a file editor and allows you to move forward and backward, go to end or start immediately.

Prepare yourself for a role working as an Information Technology Professional with Linux operating system

Conclusion

Now you have learned about cat, tac, more and less Linux commands and how to use them.

Thanks for your time. If you face any problem or any feedback, please leave a comment below.

Cat(concatenate) command is very frequently used in Linux. It reads data from the file and gives their content as output. It helps us to create, view, concatenate files. So let us see some frequently used cat commands.

1) To view a single file
Command:

2) To view multiple files
Command:

3) To view contents of a file preceding with line numbers.
Command:

4) Create a file
Command:

5) Copy the contents of one file to another file.
Command:

6) Cat command can suppress repeated empty lines in output
Command:

7) Cat command can append the contents of one file to the end of another file.
Command:

8) Cat command can display content in reverse order using tac command.
Command:

9) Cat command can highlight the end of line.
Command:

10) If you want to use the -v, -E and -T option together, then instead of writing -vET in the command, you can just use the -A command line option.
Command

11) Cat command to open dashed files.
Command:

12) Cat command if the file has a lot of content and can’t fit in the terminal.
Command:

13) Cat command to merge the contents of multiple files.
Command:

14) Cat command to display the content of all text files in the folder.
Command:

15) Cat command to write in an already existing file.

Command :

This article is contributed by Pranav. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected] See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

The cat is one of the most frequently used commands in Linux which is used to print the content of a file on the standard output. This command is also used to create, append the content of one file to the end of another file, and view the content of a file.

The tac command is the reverse of the cat command in Linux. It is rarely used to concatenate and print files in reverse. It prints the last line first and the first line in the last.

In this article, I will discuss the usage of the tac command along with some examples.

The syntax of the tac command

The syntax of how to use the tac command in Linux is given below.

Where you can use the given options with tac command.

-b , –before – This option will attach the separator before instead of after
-r , –regex – This will interpret the separator as a regular expression
-s , –separator =STRING – This makes tac command use STRING as the separator instead of the newline
–help – The option is used to display the help page
–version – Display the version information of tac and exit

Examples of using tac command in Linux

The following examples show the usage of the tac command in Linux.

Let’s say we have a file named countries.txt which contains names of some countries.

Using the cat command you can see the original content of this file is displayed in the given image.

How to use the linux cat and tac commands

Using tac command without any options

If you print the content of the given file using the tac command it will get printed in reverse order.

You can see the output of this command in the given image.

How to use the linux cat and tac commands

How to make tac use a custom separator

To make tac use a custom separator( instead of a newline) you need to use the option -s this will separate the content of a file based on a string or a keyword from the file.

This will produce the given output.

Now when you use a comma as a separator then the output of the above command will look like as it is given in the image below.

Using option -b with tac command

If you want to attach the separator before instead of after then use the option -b with tac command.

From the output of this command, you can see the difference in using separator after and before.

For more information, you can see the man page of the tac command.

Conclusion

I hope you understand the use of the tac command in Linux. Now if you have a query then leave it in the comment below.

How to use the linux cat and tac commands

Image credits: Jeff Macharyas, CC BY-SA 4.0. Donald, the cat.

The tac command is essentially the cat command, but its purpose is to concatenate files in reverse. Like cat, it has a convenient fallback mode to print to standard output (STDOUT) if no output file is provided, making it one of those commands that are more often used as a lazy pager—like less and more—than the function it is named for.

The cat command is often overused and abused, and tac is often taken as a joke command like ddate or cowsay. It often gets paraded out in April Fool’s day articles detailing stupid terminal tricks. So, it may come as a surprise that tac actually has a legitimate reason to exist.

It’s actually a useful command.

What is the purpose of tac?

The tac man page does a rather poor job of describing its own function:

Taking that statement as it’s written, tac should print the last line of a file, then print the file starting back at line one:

That’s not what it does, though. Its info page is much clearer:

Ignoring the fact that tac gives you everything in reverse, it has a few surprisingly useful and unique options.

Tac and separators

As the info page indicates, the file doesn’t have to be delimited by line, meaning that tac is equally as effective with, for example, a CSV file. You define a file’s separator character with the –separator or -s option, along with the delimiter used in the file.

For a CSV file, the character is probably a comma (,), but you can define any character. If a file doesn’t terminate with the separator character, though, then you get an unexpected result:

There is no separator character between the first two items. The file’s final record (the string following the final separator, in this case, a comma) is not itself followed by a comma, so it’s treated as a non-record by tac. To account for this issue, use the –before or -b option, which places the separator character before each record:

The separator character doesn’t have to be a single character. It can also be a regular expression (regex).

Tac and regular expressions

A full explanation of regex is out of scope for this article, but it’s worth mentioning that extended POSIX is supported by means of an environment variable . Extended regex greatly enhances the readability of a regular expression, and for the sake of simplicity, that’s what this example uses. Assume you have a file containing strings all separated by integers:

More Linux resources

You can reliably predict that the strings you care about are separated by integers, but you cannot reliably predict what those integers will be. That’s exactly the problem regex is meant to solve.

To use regex in your tac command, use the –regex or -r option before your –separator definition. Also, unless it’s already set in your environment, you must activate the REG_EXTENDED environment variable. You can set this variable to anything but zero to activate it, and you can do that in all the usual ways:

  • Export the variable for the shell session you’re using.
  • Set the environment variable in your shell configuration file (such as

The regex option doesn’t handle non-terminated records well, though, even using the –before option. You may have to adjust your source file if that feature is important to you.

When to use tac

These simple yet useful parsing options make tac worth using as an uncomplicated, minimalist parsing command. For those simple jobs that aren’t quite worth writing an AWK or Perl expression for, tac just might be a sensible solution.

The tac command is limited, obviously, because it doesn’t manipulate records in any way aside from reversing them. But sometimes that’s the only list manipulation you need.

For instance, if you’re packaging software for distribution, it’s not unusual to have a list of dependencies that are required for installation. Depending on how you gathered this list, you may have it in the order you established the dependencies were required instead of the order in which they must be installed.

This practice is relatively common because compiler errors hit the high-level dependencies first. That is, if your system is missing libavcodec then GCC stops and alerts you; but since GCC hasn’t gotten a chance to probe your system for libvorbis and libvpx, for example, it can’t tell you that those dependencies are also missing (and, often, required to exist on your system before compiling libavcodec).

So, your list of dependency grows in top-down form as you discover what libraries your system needs to build the libraries that the libraries need (and so on). At the end of such a process, tac is the quick and easy way to reverse that list.

Another common annoyance is log files. Entries are generally appended to a log file, so admins use tail to see the latest errors. That works well, but there are times you want to see a “chunk” of entries without knowing how far back you need to go. The tac command piped to less or more puts the latest entries at the top of your screen.

Finally, many configuration files have no clear termination marker for a given section. You can look up awk and sed commands to devise a way to determine when a block in a config file ends, or you can use tac to reverse the order such that once your parser has found the first relevant entry in that block, it also knows when to stop reading, because what used to be the header is now a footer.

Tac on

There are plenty of other great uses for tac, and probably a bunch of reasons that tac is too rudimentary to be a solution. Your system likely has it installed, however, so remember this command the next time you find that edge case in your workflow that really really needs to be attacked in reverse.

The cat command is one of the most useful Linux commands you can learn. It derives its name from the word concatenate and let you create, merge or print files in the standard output screen or to another file and much more.

It does not require you to install anything since it comes pre-installed with the coreutils package in any Debian or Red Hat based system.

In this tutorial, we will cover the common usages of the Linux cat command explaining its features.

Cat Command Syntax

Before we start exploring the article’s subject, we should log into the VPS using SSH, and quickly check the basic syntax. The command takes a filename as an argument along with options to specify particular operations.

To find all the available options, just type cat –help from the terminal.

Creating a File with the Cat Command

Using the cat command you can quickly create a file and put text into it. To do that, use the > redirect operator to redirect the text in the file.

The file is created, and you can begin populating it with text. To add multiple lines of text just press Enter at the end of each line. Once you’re done, hit CTRL+D to exit the file.

To verify that the file is indeed created by the command used above, just use the following ls command in the terminal:

Viewing the Content of a File with the Cat Command

This is one of the most basic usages of the cat command. Without any options, the command will read the contents of a file and display them in the console.

To prevent scrolling large files, you might want to add the option | more to output through the less or more display:

You can also display the content of more than one file. For example, to display content of all text files, use the following command in the terminal:

Redirecting Content Using the Cat Command

Rather than displaying the contents of a file in the console you can redirect the output to another file using the option >. The command line would look like this:

If the destination file does not exist then the command will create it, or overwrite an existing one by the same name.

To append the contents of the destination file, use the >> option along with the cat command:

Concatenating Files with the Cat Command

This command also lets you concatenate multiple files into a single one. Basically it functions exactly like the redirection feature above, but with multiple source files.

Like earlier, the above command will create the destination file if it does not exist, or overwrite an existing one with the same name.

Highlighting Line Ends with the Cat Command

The cat command can also mark line ends by displaying the $ character at the end of each line. To use this feature, use the -E option along with cat command:

Display Line Numbers with the Cat Command

With the cat command you can also display the contents of a file along with line numbers at the beginning of each one. To use this feature, use the -n option with cat command:

Displaying Non-Printable Characters with the Cat Command

To display all non-printable characters use the -v option along with cat command like in the following example:

To display tab characters only, use -T:

The tab characters will be shown as ^I

Suppressing Empty Lines with the Cat Command

To suppress repeated empty lines, and safe space on your display you can use the -s option. Keep in mind that this option will keep one blank line by removing the repeated empty lines only. The command would look like this:

Numbering Non-Empty Lines with the Cat Command

To display non-empty lines with line numbers printed before them use the -b option. Remember the -b option will override the -n option:

Displaying a File in Reverse Order With the Cat Command

To view the contents of a file in reverse order, starting with the last line and ending with the first, just use the tac command, which is just cat in reverse:

Conclusion

That’s it. You now know all the basic features and functions of the cat command. You will now have the basic understanding to put it to good use. For more information on the cat command, you can always invoke manual page of cat with the command man cat !.

We hope this article helped you better your Linux Terminal skills. See you in the next one!

Learn More Linux Commands for Reading Files

Edward is a Content Editor with years of experience in IT as a writer, marketer, and Linux enthusiast. Edward’s goal is to encourage readers to establish an impactful online presence. He also really loves dogs, guitars, and everything related to space.

Are you looking for the best CAT command in linux with examples? You are at the right place to get the best CAT command examples guide.

List of content you will read in this article:

  • 1. What is CAT Command?
  • 2. List of CAT Command in Linux with Example
  • 3. Conclusion

CAT is an abbreviation of “Concatenate”. Whether you are an educator or a student, you must be aware of this term. It is an extremely common and widely used command in the coding world.

When it comes to Linux or UNIX commands, this command is no newbie.

First, let us introduce you to the meaning of CAT.

What is CAT Command?

CAT command helps to create the single file as well as multiple files, concatenate them, and redirect the output in the files or terminal itself.

Additionally, it displays the content of one or more files without actually opening them for editing.

Moving on, here are some prerequisites first.

  • Linux system
  • Terminal Window or Command line

List of CAT Command in Linux with Example

Now, we are presenting some commonly used CAT commands in Linux with examples and output screens too which will help you get familiar with it. for you. Have a look!

Here is a syntax in order to know how to use the CAT command in Linux?

1. How to create a new file?

If you want to create file in Linux named, A.txt and B.text. Now, follow these steps to reach the conclusion.

Step 1: Go on the terminal window and write the following command:

Step 2: After this, type any text as you want.

Step 3: Now, press the Ctrl key and press d.

Step 4: Repeat the same process for the other file named B.txt

Step 5: Again type your desired content and press Ctrl + d.

Moving on, In order to look at the contents of a single file, here is the syntax:

Let us look at the following command if you want to see the contents of a single file:

Here, you have the liberty to display the contents of a single file as well as multiple ones. It’s up to you.

In order to view the contents of multiple files, use:

cat file1.txt file2.txt

2. How to view the contents with line numbers in a file?

Here is the command:

cat [options] filename(s)

The term ‘options’ helps you to add a set of instructions to your cat command in linux. Now, what kind of instructions?

Let us tell you.

For instance, use -n option to see the content with numbered lines.

This command helps you to show the content with numbered lines.

  1. Welcome to Linux
  2. Enjoy coding

3. How to use More and Less by cat command?

There are instances where the size of the file is too large. In such cases, the content doesn’t fit in the terminal window. Here, you can use these parameters to solve the issue.

Here is the command:

4. How to append standard output by using Redirection Operator?

If you want to append a file in an already existing file, then you can use the following command:

This will help to append the contents of the a1 file to the contents of the a2 file.

5. How to redirect the contents of a Single File in Linux?

The contents of the file are put further in a file.

cat a1.txt > b1.txt

In this case, the contents of the a1 file will be redirected to file b2. However, if the destination file is not mentioned, it will be automatically created.

Now, when you type the following command,

You will see the contents of the a1 file in b1!

6. How do you redirect the contents belonging to multiple files?

If you want to redirect the contents of multiple files to a single destination, then type this command:

cat a1.txt b1.txt > c1.txt

Now, the c1 file contains the overall content of both the files; a1 and b1.

7. How to display the content in reverse order?

The cat command can help you to display the content of the files in reverse order. Use tac, which is the reverse of cat

8. How to append the text to an existing file?

To begin with, use the following command first,

after adding the required text, type it, for instance:

All you have is now

Now that you check the file named a1, you will see the updated file.

9. How to combine several operations?

If you want to combine the output of several files, and put that into a new file, use the following cat command:

cat a1.txt b1.txt > c1.txt

The order in which you mention the files in command matters. Files are shown in that specific order in the destination file.

10. How to show TAB-separated lines?

If you are hunting for a way to display the contents of a file with tab space, use the following cat command:

All the tab spaces appear in the form of this symbol: ^I.

11. How to remove the blank lines?

In order to discard any unwanted blank lines, use the following cat command:

12. How to highlight the end of the line?

To highlight the end line of your content in the file, follow the bellow listed cat command:

13. How to display the content of every text file in a folder?

Use the bellow listed command, and find the solution:

By using this, you will see all the contents of the existing files present in your folders.

14. How to erase repetitive empty lines seen in the output?

There are times when some unwanted empty lines are seen in the output, to get rid of them, here is a solution for you:

after running this cat command listed above you solve your problem.

15. How to open dashed files?

To open some dashed files, use this command:

You will get the entire data of -dashfile.

16. How to merge the contents of more than one file?

To merge multiple files, you have to follow below-given cat command:

After merging the contents of all the files, the combined data will be represented in the merged file.

Conclusion

We hope you have a better grasp of the CAT command in Linux with examples. In the Linux world, the above-stated CAT commands are generally the most widely used Linux commands. They are simple and make your work easier. You must have noticed that inside the article vehicle reading it!

Practice these basic CAT commands on your console, and try to execute them in the code. We hope that the information provided above-added value to your knowledge and widened your knowledge base.

How to use the linux cat and tac commands

In Linux, the cat command is one of the most commonly used commands. cat which stands for “concatenate”, can read, write and concatenate file contents to standard output. The cat command is usually used to view the contents of one or more text files, combine files by adding contents of one file to another and create new files.

In this tutorial, we will learn how to use the cat command to its full potential with examples.

General Syntax

The [options] allows you to use different arguments to the command.

[filename/filenames] is where you can specify the name of a file or multiple files that you wish to display.

Create a new file

Using the cat command, you can create a new file and add content.

When you create a file in this manner, the cursor is placed on a new line where you can type your contents. After you have written the desired content, you can use Ctrl+D to finish editing and save it.

Display Contents of a file

You may use the cat command to display the contents of a file by simply typing cat followed by the filename.

You can use more or less command if you want to view file page by page.

Display Contents of Multiple files

The cat command can be used to display the contents of multiple files at a time. You can use the cat command followed by the list of filenames separated with spaces.

Copy Contents from one file to another

Using the (>) operator in the cat command, we can copy the contents from one file to another.

If the [filename2] does not exist, then the cat command automatically creates a new one and copies the file of [filename1] to [filename2] .

The command will copy the content from Test1.txt and overwrites it in Test2.txt . Instead of overwriting it, you can also append a source text file to the destination text file using the (>>) operator.

Display Line Number in a file

All the not-empty files can be displayed using the -b flag along with the cat command and file name.

If you want to display the lines with no characters as well then, the -n flag can be used along with the cat command and filename.

Concatenate a file or multiple files

If you want to view the contents of multiple files at once, use the cat command to concatenate them.

You can also combine multiple files into a single file by creating a new file or updating an existing one using the (>) operator.

Since Test4.txt does not exist, it creates and a new file called Test4.txt and concatenates the contents of Test1.txt , Test2.txt , and Test3.txt in Test4.txt .

Display End of each line in a file

You can determine the end of a line in a file using the cat command. Sometimes there are hidden characters such as spaces at the end of a line that can bring error or discover problems. You can use the cat command with the -E flag to show dollar ($) as an end of line character.

Reduce Blank Lines

When you display the contents in a file, it might be disturbing to see lots of blank lines. The cat command along with -s can be used to remove repeated blank lines from the output. The -s option in the cat command displays only one blank line and compresses the repeated ones.

The first output is without using the -s option and the second output is after using the -s option.

Show Tabs

The -T option along with the cat command displays the file content as well as the tab space within the text.
The tab spaces are denoted by the symbol ^I.

The first output is without using the -T option and the second output is after using the -T option.

Display contents of a file in reverse order

The tac command is the inverse of the cat command. tac will display the output in the reverse order of the text file’s contents.

The first output is obtained with the cat command and the second output is obtained using the tac command.

Use the help command if you want to learn more about the cat command or if you have any confusion.

Conclusion

In this tutorial, we learned about the cat command, its usage with various options, and examples. Cat is a useful command that lets you create and view multiple kinds of text files. Multiple files can be displayed at the same time in multiple ways using the cat command.

On Unix-like operating systems, the tac command catenates and prints the contents of files, in reverse, line by line.

This page covers the GNU/Linux version of tac.

Description

tac (which is “cat” backwards) concatenates each FILE to standard output like the cat command, but in reverse: line by line, printing the last line first. This is useful (for instance) for examining a chronological log file where the last line of the file contains the most recent information.

If no FILE is specified, or if the FILE is specified as ““, tac reverses the contents of standard input.

Syntax

Options

-b, –before Attach the line separator before each line of output instead of after.
-r, –regex Interpret the line separator as a regular expression (useful with the -s option, see below).
-s,
–separator=STRING
Use STRING as the line separator instead of a newline.
–help Display command help and exit.
–version Output version information and exit.

Examples

Prints the lines of file1.txt in reverse, from last line to first.

Related commands

cat — Output the contents of a file.
tail — Print the last lines of a text file.

This tutorial explains Linux “tac” command, options and its usage with examples.

DESCRIPTION

tac (which is “cat” backwards) concatenates each FILE to standard output just like the cat command, but in reverse: line-by-line, printing the last line first. This is useful (for instance) for examining a chronological log file in which the last line of the file contains the most recent information.

If no FILE is specified, or if the FILE is specified as “-“, tac reverses the contents of standard input.

SYNOPSIS

OPTIONS :

-b, –before
attach the separator before instead of after
-r, –regex
interpret the separator as a regular expression
-s, –separator=STRING
use STRING as the separator instead of newline

EXAMPLES

1. Print the lines of file1.txt in reverse, from last line to first.

The word tac is reverse of the word cat. The tac command functionality is also reverse of the cat command. cat command prints the file. tac command prints the file in reverse order with the last line first as shown below.

2. Using the other options

In this example the file records contains multiline records, each started with a line (^…$) that starts with —, followed by a number ([0-9]+) and an optional sequence of minus signs (-*). One can see the order of lines in each record and its header line are preserved.

Sanfoundry Global Education & Learning Series – 1000 Linux Tutorials.

Related Posts:

  • Apply for Programming Internship
  • Practice Programming MCQs
  • Buy Information Technology Books
  • Apply for Linux Internship
  • Buy Linux Books

Recommended Articles:

Additional Resources:

Popular Pages:

Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

How to use the linux cat and tac commands

Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & technical discussions at Telegram SanfoundryClasses.

  • Open with Desktop
  • View raw
  • Copy raw contents Copy raw contents

Copy raw contents

Copy raw contents

The cat command

The cat command allows us to create single or multiple files, to view the content of a file or to concatenate files and redirect the output to the terminal or files.

The “cat” stands for ‘concatenate.’ and it’s one of the most frequently used commands in the Linux terminal.

Examples of uses:

  1. To display the content of a file in terminal:
  1. To display the content of multiple files in terminal:
  1. To create a file with the cat command:
  1. To display all files in current directory with the same filetype:
  1. To display the content of all the files in current directory:
  1. To put the output of a given file into another file:
  1. Use cat command with more and less options:
  1. Append the contents of file1 to file2:
  1. To concatenate two files together in a new file:
  1. Some implementations of cat, with option -n, it’s possible to show line numbers:

Additional Flags and their Functionalities:

Short Flag Long Flag Description
-A –show-all equivalent to -vET
-b –number-nonblank number nonempty output lines, overrides -n
-e equivalent to -vE
-T Display tab separated lines in file opened with cat command.
-E To show $ at the end of each file.
-E Display file with line numbers.
-n –number number all output lines
-s –squeeze-blank suppress repeated empty output lines
-u (ignored)
-v –show-nonprinting use ^ and M- notation, except for LFD and TAB
–help display this help and exit
–version output version information and exit

The tac command

tac is a Linux command that allows you to view files line-by-line, beginning from the last line. (tac doesn’t reverse the contents of each individual line, only the order in which the lines are presented.) It is named by analogy with cat .

Examples of uses:

  1. To display the content of a file in terminal:
  1. This option attaches the separator before instead of after.
  1. This option will interpret the separator as a regular expression.
  1. This option uses STRING as the separator instead of newline.
  1. This option will display the help text and exit.
  1. This option will give the version information and exit.

Additional Flags and their Functionalities:

Short Flag Long Flag Description
-b –before attach the separator before instead of after
-r –regex interpret the separator as a regular expression
-s –separator=STRING use STRING as the separator instead of newline
–help display this help and exit
–version output version information and exit

You can’t perform that action at this time.

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.

In this article we will discuss the Linux tac command, which is basically the opposite of the cat command. As we learned in an earlier article, the cat command is basically used for printing file contents to the standard output starting with the first line. The tac command does the the reverse and prints the file contents starting with the last line and working up to the first line.

The options to each command are different but, tac has a couple of options that can be used in some interesting ways.

Basic Usage

The tac command will print out a file contents in reverse, showing the last line first and working it’s way up to the first line.

Below is an image showing the different output of cat vs tac.

The Tac command will also take input form STDIN (Standard input) and reverse it.
NOTE: You must use CTRL+D to exit.

You can also use redirection, which we covered in the cat tutorial already.

Using the Custom Separator

The tac command has different options that cat. For example there are not -n, -e, or -T options in tac. But there is one trick it has that cat does not. That is the custom separator which is useful and fun although I am struggling to fine a practical use for it.

As an example, let’s use a comma separated file, like this:

Normally, tac reads files from last LINE to the first. Not last item on the line. That is because the default separator is a new line. We can change the default separator to be any STRING, or even a regex. Let’s change the separator to a comma so we can get a reverse list of the names in the file.

You can use a regular expression for the customer separator as well. In this example we will tell tax to use any digital. Let’s say we had a list of animals and a number representing how many of each we had.

We can use tax and a regular expression to use the digit as a separator.

Conclusion

The Linux tac command is a fun and rarely used command. It is basically the opposite of the cat command as it prints output from last line to first. The customer separator option is a fun little tool, but I have yet to find a practical use for it.

I would love to hear any use cases you have come across, please leave them in the comments below.

The cat command in Linux concatenate files and displays the output to the standard output (usually, the shell).

One of the most common uses of cat is to display a file to the screen and also to create a file on the fly and allow basic editing straight at the terminal.

How to Create a File Using ‘cat’

To create a file using the cat command enter the following in the terminal window:

When you create a file in this manner, the cursor will be left on a new line, and you can start typing. This technique offers a great way to start a text file. To finish editing the file, press Ctrl+D. The file saves with whatever you used for filename.

Test that the process worked by typing the ls command:

You should see your new file, and the size should be greater than zero.

How to Display a File Using ‘cat’

The cat command displays a file to the screen as well. All you need to do is eliminate the greater than symbol as follows:

To view the file page by page use the more command:

Alternatively, you can use the less command as well:

How to Show Line Numbers

For all the non-empty lines in a file use the following command:

If there are lines with no characters at all they won’t be numbered. To show numbers for all the lines regardless as to whether they are blank, type the following command:

How to Show the End of Each Line

Sometimes when parsing data files, programmers discover problems because there are hidden characters at the end of lines that they weren’t expecting — such as spaces. This error prevents their parsers from working correctly.

To show the dollar as an end of line character enter the following command:

As an example look at the following line of text

When you run this with the cat -E command you receive the following output:

Reducing Blank Lines

When you show the contents of a file using the cat command you probably don’t want to see when there are loads of consecutive blank lines. Use the -s switch to condense all blank lines into a single blank line:

How to Show Tabs

When you display a file that uses tab delimiters, you won’t ordinarily see the tabs.

The following command shows ^I instead of the tab, which makes it easy to see them:

Concatenate Multiple Files

The whole point of cat is concatenation. Concatenate several files to the screen with the following command:

To concatenate the files and create a new file use the following command:

Showing Files in Reverse Order

Show a file in reverse order by using the following command:

Technically this isn’t the cat command, it is the tac command, but it essentially does the same thing but in reverse.

In this article, we discuss linux filters used to process text data so as to produce useful information. This involve commands like cat, tac, od, wc, head, tail, sort and cut.

Table of contents.

  1. Introduction.
  2. cat/tac.
  3. od.
  4. wc.
  5. head.
  6. tail.
  7. sort.
  8. cut.
  9. Summary.
  10. References.

Introduction.

Text filtering is the process of taking an input stream of text and performing conversions on it before sending it to the output stream.

A filter is a program that will read standard input(file) and performs an operation on it then outputs the result to the output stream.

These filters are smaller programs which perform only a single task, we can view them as building blocks which can combine and use to build anything.

A stream is a sequence of bytes that can be read or written using functions which hide the details of the underlying device from the application. Streams can be stdin, stdout, stderr which represent the standard input, output and error streams respectively.

Throughout this article we shall use the following text file so be sure to create one,
*test.txt

cat is short for concatenate, this command is used to display file contents without having to open the file.

To view the contents of test.txt we write,

When no file has been specified, cat will read from stdin, for example, type cat without any input and continue typing input to see what happens.

You can also write to a file without opening it by writing,

After executing the command, type something into the stdin, cat will read input and redirect it into the test2.txt file, now test2.txt will have the input from stdin stream.

You can stop this by ctrl+c.

To concatenate two files we can write,

We can number the concatenation of the two files by using the -n option,

We can also use tac command instead of cat.

We can also reverse all text in a file with tac by using the -r regex option and -s separator option.

To reverse a file we write,

od stands for octal dump, this command is used to display contents of a file in different formats such as octal, hexadecimal, ASCII characters, decimals, .

To display a file in octal format we write,

To display a file in hexadecimal format we write,

To display a file in ASCII characters we write,

To display a file in decimals, we write,

wc stands for word count, this command counts the words, characters and lines in a file.

To get the word count we write,

By default this command will give all three counts, that is words, characters and lines however we can use options to control this.

To get the number of lines we write,

For the number of words we use the -w option and for the number of characters we use -c option.

The head command displays the first n lines of a text file. The default number of lines in 10 if n is not specified.

To display the first 10 lines we write,

To display the first 3 lines we write,

The tail command works the same as the head command but in reverse, that is it displays lines from the bottom of a text file.

To display the last 10 lines(default), we write,

To display the last 4 lines in the text file we write,

We can also sort output alphabetically using the sort command.
To sort the file test.txt we write,

We can also decide to sort a specific column by writing,

We have used sed command to replace the | characters with white spaces, then piped the output to sort by the second column which is the first names.
This is an small example to show how the smaller commands can be combined to achieve amazing results.

Given a file of numbers we can sort it numerically using the -n option,

The cut command is used to select a specific column of a file assuming a text file is separated by columns.

It cuts a specified section by byte position, characters and field and writes it to the stdout stream.

We specify delimiters to tell the command how the sections are separated, in our case the test.txt file columns are separated by ‘|’.

To get all professions (column 6) we write,

We can also cut by using space as a delimiter,

Since our file is separated by ‘|’ we use sed to replace them with ” then apply the cut command. The output is all email addresses from the fourth column.

We can also cut by by byte by using the -b option, that is if we want only the first initials of peoples first names from test.txt we can write,

Can you sort the output from the above command?

We can also cut by character by using the -c option as follows,

To cut the first three characters from the first name we write,

Or to cut the fifth and ninth character we can write,

We can also comma-separate the value to cut as many values as we need, e.g
5, 10, 15 cuts the fifth, tenth and fifteenth characters.

We can also cut by complement pattern,

To cut the test.txt by the third characters we can write,

And, to cut it by the first four characters(id and ‘|’) so as to get a clean output, we can write,

Summary.

Filters can be used to process information in very useful ways by restructuring output to generate useful information or text modifications.

Note that some of these commands, maybe all, can be executed in git bash which can be installed in a windows environment.

References.

  1. For each of the commands you can type command –help for reference.

How to use the linux cat and tac commands

Erick Lumunge

Erick Lumunge is a passionate programmer with a computer science background who loves to learn about and use code to impact lives positively.

Improved & Reviewed by:

OpenGenus Foundation

Linux

Linux text filtering: diff, uniq, sdiff, less, more, tr, expand, unexpand

Text filtering is the process of taking an input stream, processing it and sending it to the output stream, this article is a continuation of the first part, here we learn more text processing commands.

How to use the linux cat and tac commandsErick Lumunge

Linux file permissions (chmod)

Linux systems are not only multitasking but also multi-user and this raises security concerns fortunately permissions exist to control the power of different users over files and directories. In this article we discuss these permissions, different classes of users and commands involving permissions.

How to use the linux cat and tac commandsErick Lumunge

tac command in Linux is basically the reverse of cat command . Means, using this command allows users to display the file in reverse order to standard output. In case if no file is specified while using this command, it will read the standard output.

Table of Contents

Syntax of tac Command in Linux

tac [Options] [File_Name]

Options available to use with tac

  • -b: Used for attaching separator before instead of after.
  • -r: Used for interpreting the separator as regular expression.
  • -s: Allows to use STRING as the separator.
  • –help: Displays help information and exits.
  • –version: Displays version information and exits.

Examples of tac command

1: Displaying help information

How to use the linux cat and tac commands

2: Displaying version details

How to use the linux cat and tac commands

Nishant

Nishant Verma is a senior web developer who love to share his knowledge about Linux, SysAdmin, and more other web handlers. Currently, he loves to write as content contributor for ServoNode.

cat stands for Concatenate. cat command is one of the basic command in Linux & Unix. It is used to create new files, concatenate files and and also used to view the contents of files on the standard output. In this article, we will learn cat command with 16 quick examples.

Basic syntax of cat command :

How to use the linux cat and tac commands

Example 1) Create file with cat command

Let’s suppose i want to create a new file with name ‘linux_world’. Type the following cat command followed by the text you want in to insert in the file. Make sure you type ‘Ctrl-d’ at the end to save the file.

Example 2) View the Content of a file

To display or view the content of existing file using cat command, use the below syntax

To view the contents of linux_world file, run

Example 3) View the content of multiple files

To view the content of multiple files with cat command, then type cat followed the file names, example is shown below

Above command will display output of three files on the terminal.

Example 4) View content page wise

For example if we have a large file whose contents can’t be displayed at once on the screen. So in that case we can use more and less command with cat to view the contents page wise.

Example 5) cat command without filename arguments

if we don’t specify any arguments in the cat command then it will read the inputs from the keyboard attached to the system. Type some text after entering the cat command.

Now press ‘Ctrl-d‘ to inform cat that it has reached end of file (EOF). In this case it will display the line of text twice because it copies std input to std output.

Example 6) View the content with line numbers

Use ‘-n’ option in cat command to view content of a file along with the line numbers.

In case, if your file has blank lines , then above command will also display the number of blank lines as well, so to remove the numbering of blank lines , we can use ‘-b‘ option in place of ‘-n’ in the above command.

Example 7) Copy content from one file to another

Using greater than ‘>‘ symbol in cat command, we can copy the contents of one file to another , example is shown below :

In this case, if there are any contents in linux_text file then it will be overwritten by the contents of linux_world file

Example 8) Append content of one file to another

Using double greater than symbol ‘>>‘ in cat command, we can append the contents of one file to another. Example is shown below :

Above Command will append the contents of /etc/passwd file to linux_text file at the end. Use cat command to verify the contents of linux_text file.

How to use the linux cat and tac commands

Example 9) Redirecting the output of multiple files into a single file

cat command can also be used to merge the content of multiple files into a single file, example is shown below:

Above command will merge the output of 3 files into a single file ‘ linux_merge_tex t’.

How to use the linux cat and tac commands

Example 10) Getting input using standard input operator

Use ‘<‘ symbol in cat command to get input from standard input operator.

Above cat command is getting input from the file using std input operator ‘<‘

Example 11) Sorting the output of multiple files into a single file

cat command can also sort the content of multiple files and merge it into a single file.By default sorting will done on the alphabetic order, if you want the sorting on the basis of numbers then use ‘-n’ option in the sort command.

Example 12) Insert $ at end of each line

If you wish to append $ (dolar) symbol at end of each line in the file then use ‘-E’ option in cat command.

As we can see in the above output, $ is appended at the end of each line.

Example 13 Display tab spaces in the content

Let’s assume we have a file which has some tab spaces in the content. To view the tab spaces in the contents of a file with cat command, use using -T option. Example is shown below:

Let’s create a file with some tab spaces.

Now display these tab spaces as ^I

Example 14) Squeeze repeated blank lines

Use ‘-s’ option in cat command to suppress the repeated blank lines. When we use -s option in cat command then it only show one blank line and will squeeze repeated blank line.

Let’s take am example of file ‘linux_blank’ , which consists of multiple repeated blank lines.

How to use the linux cat and tac commands

Now remove the repeated blank lines in the output using below command.

Example 15 ) View the content in reverse order

tac is the reverse of cat command. tac will display the output in revers order example is shown below

Example 16 ) Display non-printing characters (-v)

-v option in the cat command is used to show the non-printing characters in the output. This option become useful when we are suspecting the CRLF ending lines, in that case it will show ^M at the end of each line.

That’s all from article and i hope these examples are informative to you. Please do share your feedback and Comments.

Read Also : 11 df command examples in Linux

6 thoughts on “16 Quick Cat Command Examples in Linux”

The following command does not work.
sudo cat hosts >> /etc/hosts.
That’s why. I do …
1) sudo su
2) cat hosts >> /etc/hosts
Is there a single command to achieve the result of the above two commands ?

Do
$ cat hosts | sudo tee /etc/hosts

You can do the following:

cat hosts | sudo tee /etc/hosts

tee (which is executed with sudo rights) will write the output to /etc/hosts and print it to standard out.

Did you try
su -c ‘cat hosts >> /etc/hosts’

Be careful, Examples 4 and 11 are winners of the “Useless use of cat award,” which is often the case when you pipe cat output to another command.

how do you modify the cat command to show only the last paragraph of a textfile

I’d like to reverse the order of lines in a text file (or stdin), preserving the contents of each line.

So, i.e., starting with:

I’d like to end up with

Is there a standard UNIX commandline utility for this?

25 Answers 25

Also worth mentioning: tac (the, ahem, reverse of cat ). Part of coreutils.

Flipping one file into another

How to use the linux cat and tac commands

Reference: FreeBSD, NetBSD, OpenBSD and OS X manual pages.

tail: invalid option — r Try `tail –help’ for more information. look like its new option

(Explanation: prepend non-initial line to hold buffer, swap line and hold buffer, print out line at end)

Alternatively (with faster execution) from the awk one-liners:

If you can’t remember that,

On a system with GNU utilities, the other answers are simpler, but not all the world is GNU/Linux.

How to use the linux cat and tac commands

at the end of your command put: | tac

tac does exactly what you’re asking for, it “Write each FILE to standard output, last line first.”

tac is the opposite of cat :-).

If you happen to be in vim use

Try tac , which works on Linux, and if that doesn’t work use tail -r , which works on BSD and OSX.

Try the following command:

For cross OS (i.e. OSX, Linux) solution that may use tac inside a shell script use homebrew as others have mentioned above, then just alias tac like so:

For linux debian

How to use the linux cat and tac commands

I really like the “tail -r” answer, but my favorite gawk answer is.

The simplest method is using the tac command. tac is cat ‘s inverse. Example:

EDIT the following generates a randomly sorted list of numbers from 1 to 10:

where dots are replaced with actual command which reverses the list

tac

python: using [::-1] on sys.stdin

If you want to modify the file in place, you can run

This removes the need to create a temporary file and then delete or rename the original and has the same result. For example:

Based on the answer by ephemient, which did almost, but not quite, what I wanted.

How to use the linux cat and tac commands

This will work on both BSD and GNU.

I see lots of interesting ideas. But try my idea. Pipe your text into this:

which assumes that the character ‘

‘ is not in the file. This should work on every UNIX shell going back to 1961. Or something like that.

For Emacs users: C-x h (select the whole file) and then M-x reverse-region . Also works for only selecting parts or the lines and reverting those.

It happens to me that I want to get the last n lines of a very large text file efficiently.

The first thing I tried is tail -n 10000000 file.txt > ans.txt , but I found it very slow, for tail has to seek to the location and then moves back to print the results.

When I realize it, I switch to another solution: tac file.txt | head -n 10000000 > ans.txt . This time, the seek position just needs to move from the end to the desired location and it saves 50% time!

Take home message:

Use tac file.txt | head -n n if your tail does not have the -r option.

How to use the linux cat and tac commands

You may use Perl on the commandline:

How to use the linux cat and tac commands

I had the same question, but I also wanted the first line (header) to stay on top. So I needed to use the power of awk

PS also works in cygwin or gitbash

How to use the linux cat and tac commands

You can do it with vim stdin and stdout . You can also use ex to be POSIX compliant. vim is just the visual mode for ex . In fact, you can use ex with vim -e or vim -E (improved ex mode). vim is useful because unlike tools like sed it buffers the file for editing, while sed is used for streams. You might be able to use awk , but you would have to manually buffer everything in a variable.

The idea is to do the following:

  1. Read from stdin
  2. For each line move it to line 1 (to reverse). Command is g/^/m0 . This means globally, for each line g ; match the start of the line, which matches anything ^ ; move it after address 0, which is line 1 m0 .
  3. Print everything. Command is %p . This means for the range of all lines % ; print the line p .
  4. Forcefully quit without saving the file. Command is q! . This means quit q ; forcefully ! .

How to make this reusable

I use a script I call ved (vim editor like sed ) to use vim to edit stdin . Add this to a file called ved in your path:

I am using one + command instead of +’%p’ +’q!’ , because vim limits you to 10 commands. So merging them allows the “[email protected]” to have 9 + commands instead of 8.

tac command in Linux is used to concatenate and print files in reverse. This command will write each FILE to standard output, the last line first. When no file is specified then this command will read the standard input. Example: It will print files in reverse.

What is TAC in bash?

Also known as reverse cat, tac a simple command-line utility that lets you reverse lines in output using the | builtin pipe operator and tac. That is, if you have a command, left-hand side (lhs), and want to reverse the contents of its output, all you would do is type lhs | tac. That’s it!

How do I use cat command in Mac terminal?

To look at the contents of a text-based configuration file, use cat or less . Generally, you’ll use less because it has more options (such as searching). To use less , enter the command name followed by the name of the file you want to view.

What is the difference between CAT and TAC?

Tac is practically the reverse version of cat command (also spelled backwards) which prints each line of a file starting from the bottom line and finishing on the top line to your machine standard output.

What is the use of CD in Linux?

cd command in linux known as change directory command. It is used to change current working directory. In the above example, we have checked number of directories in our home directory and moved inside the Documents directory by using cd Documents command.

How do I stop a command in Terminal?

Use Ctrl + Break key combo. Press Ctrl + Z . This will not stop program but will return you the command prompt.

How do you close a cat command on a Mac?

Now simply enter the information you want in the file followed by the CTRL+D (hold down Ctrl Key and type ‘d’) to exit.

Which command changes file permissions?

The chmod command enables you to change the permissions on a file. You must be superuser or the owner of a file or directory to change its permissions.

Which is the most important option of the TAC command?

One of the most important option of the command is represented by the -s switch, which separates the contents of the file based on a string or a keyword from the file. Next, most important usage of tac command is, that it can provide a great help in order to debug log files, reversing the chronological order of log contents.

Is the TAC command the same as the cat command?

Same as cat command, tac does an excellent job in manipulating text files, but it should be avoided in other type of files, especially binary files or on files where the first line denotes the program that will run it.

How to run TAC with a filename?

Simple, just run the ‘tac’ command with a filename as input. So you can see the output produced by tac is exactly opposite of what cat produced. Q2. How to make tac use custom separator (not newline)? For this, you’ll have to use the -s option. For example, the following command That’s because newline is the default separator for tac.

How do you do TAC in Linux command line?

Once you are done with that, press Ctrl+d to signify you’re done, and then tac will produce its output on STDOUT. As you can see, tac is easy to understand and work with. The number of command line options it offers is limited, and we’ve discussed most of them here.

There are several commands that display information about a file in the read-only format. The file-viewing commands include the following:

  • cat
  • more
  • tail
  • head
  • wc

cat Command

The cat command displays the content of one or more text files on the screen without pausing.

Do not use the cat command to read binary files. Using the cat command to read binary files can cause a terminal window to freeze. If your terminal window freezes, close the terminal window, and open a new terminal window.

more Command

The more command displays the content of a text file one screen at a time.

message appears at the bottom of each screen, where n% is the percentage of the file that has been displayed. When the entire file has been displayed, the shell prompt appears.

When the –More–(n%)prompt appears at the bottom of the screen, you can use the keys described in the table to scroll through the file.

Keyboard Command Action
Space bar Moves forward one screen
Return Scrolls one line at a time
b Moves back one screen
h Displays a help menu of features
/string Searches forward for pattern
n Finds the next occurrence of pattern
q Quits and returns to the shell prompt

head Command

The head command displays the first 10 lines of a file.

You can change the number of lines displayed by using the -n option. For example, to display the first five lines of the /var/log/messages file, enter the head command with the -n option set to 5.

tail Command

The tail command displays the last 10 lines of a file.

You can change the number of lines displayed by using the -n or +n options.
– The -n option displays n lines from the end of the file.
– The +n option displays the file from line n to the end of the file.

For example, to display the last four lines of the /var/log/messages file, enter the tail command with the -n option set to 4.

For example, to display line 10 through the end of the data.txt file, enter the tail command with the +n option set to 10.

wc Command

The wc command displays the number of lines, words, and characters contained in a file.

You can use the following options with the wc command.

Symbol Description
-l Line count
-w Word count
-c Byte count
-m Character count

When you use the wc command without options, the output displays the number of lines, words, and characters contained in the file. For example, to display the number of lines, words, and characters in the dante file, use the wc command.

For example, to display the number of lines in the dante file, enter the wc command with the -l option.

There are many commands to view files, and different commands have different advantages. You can select commands for different needs to improve efficiency:
cat displays the content from the first line, and outputs all the content.
tac displays the content in reverse order from the last line. And output all the content
more. According to the window size, the content of the file displayed page by page is
less and more similar, but its advantages can be turned forward, and the characters can be searched.
head only displays the first few lines
tail only displays the last few lines
nl Similar to cat -n,
I use more and less to output line numbers when displaying !

1. The function of
cat and tac cat is to continuously output the content of the file on the screen from the first line. But cat is not commonly used, because when the file is large and the number of lines is large, only part of the content can be seen when the screen cannot fit all of it.

cat syntax: cat [-n] File name
parameter description: -n: When displayed, output the line number together

for example:
[[email protected] redhat

]# cat .bashrc
# .bashrc
# User specific aliases and functions
alias rm=’rm -i’
alias cp=’cp -i’
alias mv=’mv -i’
# Source global definitions
if [-f/etc/bashrc ]; then
./etc/bashrc
fi

Add -n parameter
[[email protected]

]# cat -n .bashrc
1 # .bashrc
2
3 # User specific aliases and functions
4
5 alias rm=’rm -i’
6 alias cp=’cp -i’
7 alias mv =’mv -i’
8
9 # Source global definitions
10 if [-f/etc/bashrc ]; then
11./etc/bashrc
12 fi

The function of tac is to reverse the file from the last line and output the content data to the screen. We can find that tac is actually written in reverse as cat.

tac syntax: tac file name
such as:
[[email protected]

]# tac .bashrc
fi
./etc/bashrc
if [-f/etc/bashrc ]; then
# Source global definitions
alias mv=’mv -i’
alias cp= ‘cp -i’
alias rm=’rm -i’
# User specific aliases and functions
# .bashrc
found no, and the comparison with cat output is completely reversed. This command is not commonly used.

2.more and less (recommended)
Compared with cat and tac, more and less are very useful. The function of

more is to start the file from the first line and output the file content appropriately according to the size of the output window.
When the whole page cannot be output, you can use the “enter key” to scroll down 3 lines (my environment is 3 lines, other Linux versions may be different), or use the “space bar” to scroll down.
To exit the viewing page, press the “q” key.
In addition, more can also be used with the pipe character “|” (pipe), for example: ls -al | more

The syntax of
more : The function of the more file name

less is similar to that of more, but you can’t use more to turn the page forward, you can only turn it back.
Less can use [pageup] and [pagedown] keys to turn pages forward and backward, which looks more convenient.

The syntax of
less : less The file name

less also has a function, you can search the content you want in the file. If you want to find the weblogic string in the passwd file, then you can do it like this:
[[email protected] etc]# less passwd
and then enter:
/weblogic
Enter
if there is a weblogic string at this time, linux will highlight the character.

To exit the viewing page, press the “q” key.

3.
head and tail head and tail are usually used when only the first few lines or the last few lines of the file need to be read. The function of

head is to display

the syntax of the first few lines of the file :
head [-n number]

For example:
[[email protected] etc]# head -n 5 passwd – Only display 5 lines of content
root:x:0: 0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3 :4:adm:/var/adm:/sbin/nologin
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin

The function of tail is just the opposite of head, only the last few lines are displayed.

The syntax of
tail : tail [-n number]

For example:
[[email protected] etc]# tail -n 10 passwd
–Only display the last 5 lines userb:x :503:504::/home/userb:/bin/bash
userc:x:504:502::/home/userc:/bin/bash
zgz:x:505:505::/home/zgz:/bin/bash
myy:x:506:505::/home/myy:/bin/bash
weblogic:x:507:508::/home/weblogic:/bin/bash

4.nl The function of
nl is the same as cat -n, the same It is to output all content from the first line, and display the line number.

The syntax of
nl : nl file name

example:
[[email protected] etc]# nl

/.bashrc
1 # .bashrc

2 # User specific aliases and functions

3 alias rm =’rm -i’
4 alias cp=’cp -i’
5 alias mv=’mv -i’

6 # Source global definitions
7 if [-f/etc/bashrc ]; then
8./etc/bashrc
9 fi