Cat and Less give different output

catescape-characterslessterminal

I executed the following command

# top > /home/user/top_output.txt

Nothing Happened for a while and then i pressed Ctrl+C. When i checked the file that was created, it had the contents in it. So i fired cat command on it and it gave me this output.
cat output of the text file

But when i tried the same thing with the less command i got this.

less output of the files

According to this post the job of Cat,less or More is just to display the contents of the file not translating the encoding. Can someone please tell me what's happening here?

P.S: I'm currently using Fedora 19

Best Answer

The escape sequences ESC [ ... m are called ANSI Escape Sequences. top sends them to your terminal to make it format output in color, bold, inverted text and so on. You never see these characters when running top but you see the resulting format. You could think of it as looking at a webpage in a browser - you don't see the <html>... formatting the content.

When dumping the output of top into a file, you are saving the non-printable escape sequences with everything else. Think of it as saving view source in your browser.

The default for less is to escape terminal control characters, displaying them in a printable form.

The default for cat is to pass them through to your terminal which interprets them and makes it look "normal".

Try less -r /home/user/top_output.txt

   $ man less ...
   -r or --raw-control-chars
          Causes "raw" control characters to be displayed.  
           The default is to display control characters using the caret
           notation; for example, a control-A (octal 001) is displayed as 
           "^A". Warning: when the -r option is used, less cannot keep 
           track of the actual appearance of the screen (since this depends
           on how the screen responds to each type of control
           character).  Thus, various display problems may result, such
           as long lines being split in the wrong place.

Compare to cat -v /home/user/top_output.txt which will escape non-printable characters.

Related Question