Strange characters when the output of `ls` is redirected to a file

I want to list the components of the current working directory in a text file

ls -1 > textfile

Output looks fine with more.

1010661085645
1010729039145
1010747080245
1010849051345
1010859053445
1011046075845

However when I view this textfile with emacs, several strange characters appear

[0m[01;34m1010661085645[0m
[01;34m1010729039145[0m
[01;34m1010747080245[0m
[01;34m1010849051345[0m
[01;34m1010859053445[0m
[01;34m1011046075845[0m

Can anyone explain what is going on here?

Answer

Those “strange characters” are escape sequences for coloring the output.

This will print that number in blue color:

echo -e '\033[01;34m1010729039145\033[0m'

See man console_codes for more details.


You can tell ls in which cases it shall output colors:

   --color[=WHEN]
          colorize the output; WHEN can be 'never', 'auto', or 'always' (the default); more info below

Looks like your ls is actually an alias for ls --color=always. (Type type ls to verify.)

Usually ls --color=auto will do the right thing: It will print colors on screen but no into files.


If you really want the color in your file, your have to decide, if you want to see the actual escape sequences or the interpreted colors.

For example the less command will default to printing the actual sequences, but you can tell it to show the colors instead with the -R option:

   -R or --RAW-CONTROL-CHARS
          Like -r, but only ANSI "color" escape sequences are output in "raw" form.

Try less textfile vs. less -R textfile.

Attribution
Source : Link , Question Author : moadeep , Answer Author : michas

Leave a Comment