How to use the Linux cat and tac commands

Contents

Art of a terminal window on a Linux desktop

the cat and tac Commands display the content of text files, but there's more to them than meets the eye. Dive a little deeper and learn some productive Linux command line tricks.

These are two simple little commands, that are often dismissed for being just that: too simple to be of real use. But once you know the different ways you can use them, You will see that they are stupendously capable of doing their fair share of the heavy lifting when it comes to working with files..

The Cat Command

cat is used for browse the content of text filesand join parts of files to form a larger file.

In a moment, in the era of dial-up modem: The binary files were often divided into several smaller files for easy download. Instead of downloading a large file, pulled every smaller file. If a single file was not downloaded correctly, I would just get that file back.

Of course, so I needed a way to reconstitute the collection of smaller files into a single working binary file. That procedure was called concatenation. And that's where cat entered and where does it take its name.

Broadband and fiber connections have caused that particular need to fade, just like the screeching sounds of phone calls, Thus, What's left for cat to do today? A lot actually.

Viewing a text file

To have cat list the contents of a text file in a terminal window, use the following command.

Make sure the file is a text file. If you try to list the contents of a binary file in the terminal window, results will be unpredictable. You can end up with a locked terminal session or worse.

cat poem1.txt

The content of the poem1.txt file is displayed in the terminal window.

That's only half of the famous poem. Where is the rest? Here is another file called poem2.txt. We can do cat list the contents of multiple files with one command. All we will do is list the files in order on the command line.

cat poem1.txt poem2.txt

That looks better; now we have the complete poem.

Use cat with less

The poem is all there, But he passed the window too fast to read the first few verses. We can funnel the output from cat within less and scroll down the text at our own pace.

cat poem1.txt poem2.txt | less

Now we can go back and forth through the text in a sequence, even if it is in two separate text files.

Line numbering in a file

We can have cat number the lines in the file as it is displayed. To do this, we use the -n option (number).

cat -n poem1.txt

The lines are numbered as they are displayed in the terminal window.

Do not number the blank lines

We managed to have the lines numbered by cat, but also the blank lines between the verses are being counted. To have the text lines numbered but to ignore the blank lines, use el -b Option (number not blank).

cat -b poem1.txt

Now lines of text are numbered and blank lines are skipped.

Don't display multiple blank lines

If there are sections of consecutive blank lines in a file, we can ask cat to ignore all but one blank lines. Look at this file.

The following command will cause cat to display only one blank line from each group of blank lines. The option we need to achieve this is the -s (blank space).

cat -s poem1.txt

This does not affect the content of the file in any way; just change the shape cat show the file.

Display tabs

If you want to know if blanks are caused by spaces or tabs, you can find out using the -T option (show-tabs).

cat -T poem1.txt

The tabs are represented by the characters "^ I".

Viewing the ends of lines

You can check for trailing blanks using the -E Option (show-ends).

cat -E poem1.txt

The ends of the lines are represented by the character “$”.

Concatenate files

It makes no sense to have a poem saved in two files, with half in each. Let's join them and create a new file with the complete poem.

cat poem1.txt poem2.txt > jabberwocky.txt

let's use cat to check our new file:

cat jabberwocky.txt

Our new file contains the content of the other two files.

Add text to an existing file

That is better, but actually, it is not the complete poem. The last verse is missing. The last verse of Jabberwocky is the same as the first verse.

If we have the first verse in a file, we can add it to the end of the jabberwocky.txt file and we will have the complete poem.

In this next command, We have to use >>, Not only >. If we use only one > good Overwrite jabberwocky.txt. We don't want to do that. We want to attach text at the end.

cat first_verse.txt >> jabberwocky.txt

Let's review the content of the jabberwocky.txt file:

cat jabberwocky.txt

And to finish, all parts of the poem are together.

Redirigir stdin

You can redirect keyboard input to a file using cat. Everything you type is redirected to the file until you hit Ctrl + D. Please note that we use only one > because we want to create the file (or overwrite it, if it exists).

cat > my_poem.txt

We can start typing as soon as we issue the command. We press Ctrl + D when we're done. Later we can verify the content of the new file with:

cat my-poem.txt

That sound like a distant turbine is probably Lewis Carroll spinning in his grave at high speed.

The tac command

tac is similar to cat, but it lists the content of the files in reverse order.

Lets see that:

tac my_poem.txt

And the file is displayed in the terminal window in reverse order. In this circumstance, has no effect on your literary merits.

Using tac with stdin

Using tac without a filename will make it operate on keyboard input. Pressing Ctrl + D will stop the input stage, and tac will list in reverse order what you have typed.

tac

When Ctrl is pressed + D, the input is reversed and displayed in the terminal window.

Using tac with log files

Aside from the low-quality parlor gimmicks, may tac do something useful? Yes it can. Many log files add their most recent entries to the end of the file. Using tac (and, counterintuitively, head) we can show the last entry in the terminal window.

We use tac to list the syslog file backwards and pipe it to head. counting head to print only the first line it receives (that thanks to tac is the last line of the file), we see the last entry in the syslog file.

tac / var / log / syslog | head -1

head prints the last entry in the syslog file and then exits.

Note that head it is only printing one line, as we request, but the line is so long it wraps twice. This is why they look like three output lines in the terminal window.

Use tac with text records

The last trick tac he has up his sleeve is a beauty.

Generally, tac operate on text files working through them line by line, bottom up. A line is a sequence of characters terminated by a new line character. But we can say tac to work with other delimiters. This allows us to treat “Fragments” of data within the text file as data records.

Let's say we have a log file of some program that we need to review or analyze.. Let's take a look at its format with less.

less logfile.dat

As we can see, there is a repeating format for the file. There are three-line sequences of hexadecimal values. Each set of three hex lines has a tag line that begins with "= SEQ", followed by a sequence of digits.

If we scroll to the end of the file, we can see that there are many of these records. The last one has the number 865.

Let's suppose, for any reason, we need to work with this file in reverse order, data log by data log. The order of the three hexadecimal lines of each data record must be preserved.

We will note that the last three lines of the file begin with the hexadecimal values 93, E7 and B8, in that order.

Let's use tac to invert the file. It is a very long file, therefore we will channel it to less.

tac logfile.dat | less

That reverses the file, but it is not the result we want. We want the file to be reversed, but the lines of each data record must be in their original order.

We previously recorded that the last three lines of the file start with the hexadecimal values 93, E7 and B8, in that order. The order of those lines has been reversed. At the same time, the lines “= SEQ” now they are below each set of three hex lines.

tac to the rescue.

tac -b -r -s ^=SEQ.+[0-9]+*$ logfile.dat | less

Let's analyze that.

the -s The option (separator) informs tac what we want to use as a delimiter between our records. Dice tac don't use your frequent newline character, but use our separator instead.

the -r (regex) option says tac to treat the separation chain as a regular phrase.

the -b (before) option causes tac to list the separator before each record instead of after it (which is the frequent position of your default separator, the newline character).

the -s (separator) chain ^=SEQ.+[0-9]+*$ is decrypted as follows:

the ^ character represents the beginning of the line. This is followed =SEQ.+[0-9]+*$. This instructs tac to search for each occurrence of “= SEQ”. at the beginning of a line, followed by any sequence of digits (indicated by [0-9]), and followed by any other set of characters (indicated by *$).

We are channeling everything into less, as always.

inverted log file with correctly formed data records

Our file is now presented in reverse order with each tag line “= SEQ” Listed before your three hexadecimal data lines. The three lines of hexadecimal values ​​are in their original order within each data record.

We can check this simply. The first value of the first three lines of hex (which were the last three lines before the file was reversed) matches the values ​​from which we took a previous record: 93, E7 and B8, in that order.

That's quite a hack for a single line terminal window.

Everything has a purpose

In the world of Linux, even the seemingly simple commands and utilities can have surprising and powerful properties.

The Simple Utilities Design Philosophy they do one thing well, and that easily interact with other utilities, has led to some strange little commands, What tac. At first sight, seems a little strange. But when you look below the surface, there is an unexpected power that you can harness to your advantage.

O, as another philosophy says, “Don't despise the snake for not having horns, because who can say that he will not turn into a dragon?”

setTimeout(function(){
!function(f,b,e,v,n,t,s)
{if(f.fbq)return;n=f.fbq=function(){n.callMethod?
n.callMethod.apply(n,arguments):n.queue.push(arguments)};
if(!f._fbq)f._fbq = n;n.push=n;n.loaded=!0;n.version=’2.0′;
n.queue=[];t=b.createElement(e);t.async=!0;
t.src=v;s=b.getElementsByTagName(e)[0];
s.parentNode.insertBefore(t,s) } (window, document,’script’,
‘https://connect.facebook.net/en_US/fbevents.js’);
fbq(‘init’, ‘335401813750447’);
fbq(‘track’, ‘PageView’);
},3000);

Subscribe to our Newsletter

We will not send you SPAM mail. We hate it as much as you.