cat reads files and writes their contents to standard output, which is normally your screen. The name comes from "concatenate", meaning to join things end to end.
Showing a file
$ cat colors.txt
red
green
bluecat prints everything at once. That suits short files. For long ones, use less so you can scroll.
Joining files
Give several names and cat prints them one after another, in the order you list them:
$ cat first.txt second.txt
Hello from the first file.
Hello from the second file.Redirection
The shell can send that output into a file with >:
$ cat first.txt second.txt > both.txt> creates the file, or erases and replaces it if it already exists. >> adds to the end instead:
$ cat third.txt >> both.txtNever use a file as both input and output, as in cat a.txt b.txt > a.txt. The shell empties a.txt before cat reads it, so its old contents are lost.
Typing input
With no file name, cat reads what you type. Combined with >, this makes a quick small file:
$ cat > todo.txt
buy milk
call SamPress Ctrl+D on an empty line to signal the end of input. Remember that > replaces an existing todo.txt.
Useful options
-n numbers every output line:
$ cat -n colors.txt
1 red
2 green
3 blue-b numbers only non-blank lines, and -s squeezes repeated blank lines into one. GNU cat also has -A, which makes tabs and line endings visible. Tabs appear as ^I and each line end as $. BSD and macOS cat do not have -A, though -e and -t give similar views.
Practise redirection in the streams and text lab.
Try it
- Create two small files with
cat > name. - Join them into a third file with
>. - Append one of them again with
>>. - View the result with
cat -n.
Check your understanding
cat
All 5 sections ยท no timer
Unlimited retries
Questions from every section are combined into one assessment. Answer them all correctly to complete the article.
Your completion saves in this browser. Sign in to sync it to your account.