The Quest for Demoggifying Continues
EFY Times, a technology website from India, often provides some interesting Linux and open source news and advice. But sometimes that advice really needs to be taken with a grain of salt. An example, is 10 Basic Linux Commands for Beginners. The first item on this provided several examples of the 'cat' command which, unfortunately, are very bad examples of the use of the command - indeed they are classic examples of what has led to 'demoggification', the removal of useless cat commands. Review what was offered:
1. cat: Shows the contents of files to the screen.
Actually no. The cat command concatenates files, or standard input, and prints to standard output.
# cat file.txt
# Hello World
Where's the concatenation with this? Sure, cat works for very small files such as the example given, but if it's more than a screen in size, you'll be better off using 'less'. If it's really short, you may as well use head or tail. Also, you're running as root, right?
$ cat | wc -l
There I've taken you out of root... Why on earth are you piping word count through to cat? All you've done is add another process. Instead do
wc -l filename. Achieves the same result, costs less processes, and even less keystrokes.
$ cat | wc -w
cat | wc -c
$ cat | grep
Again, the same problem. Instead do
grep searchterm filename. Again, achieves the same result, costs less processes, and even less keystrokes.
The basic rule of thumb is don't put cat in a pipe.
So what are good, or at least better, examples of cat?
1. Concatenate Multiple Files
Really, that's what the name says.
$cat textfile1.txt textfile2.txt textfile3.txt > textfileall.txt
The cat command works particularly well with redirects. It concatenates - who would have thought it? For example, appending to the file textfileall.txt
$cat textile4.txt >> textfileall.txt
2. Create A File
The cat command will accept data from standard input which can be redirected to a file, and closed with Cntrl-D. For example,
$cat > textfilenew.txt
Let's type in some data!
3. Display Special Characters
The cat command has a number of options which can be combined to display line numbers, line numbers without blank lines, and a variety non-printing characters (e.g., tab characters, line feeds etc).
-A, --show-all equivalent to -vET
-b, --number-nonblank number nonempty output lines, overrides -n
-e equivalent to -vE
-E, --show-ends display $ at end of each line
-n, --number number all output lines
-s, --squeeze-blank suppress repeated empty output lines
-t equivalent to -vT
-v, --show-nonprinting use ^ and M- notation, except for LFD and TAB
$cat -nA textfileall.txt
4. Reverse cat with tac
Whilst not the cat command, a related command is tac, which can print to standard output in reverse line order.