The cat
or concatenate command writes files to the standard output (the text you see on your screen in your terminal).
meanii ✓ cat hello.txt
cat
is often the easiest way to quickly inspect the contents of a file. It becomes especially powerful when piped into grep
:
meanii ✓ cat guest_list.txt | grep Lucy
‘Piping’, i.e. the | character, allows you to chain commands together, using the output of the left-hand side command as input to the command on the right-hand side. It’s a useful technique that allows you to do complex output processing by combining simple commands together.
One of the most common uses of the pipe command is to grep the result of the left-hand side command. grep, a catchy acronym for the not-so-catchy name Global Regular Expressions Print, is a simple utility that searches input for a line that matches the given pattern, in this case, a line containing the word ‘Lucy’.
Another very common use of cat and grep together is searching for a specific event in a large log file, i.e. /var/log/messages
.
meanii ✓ cat /var/log/messages | grep '500 Internal Server Error'
grep can be used for searching any kind of output, not just file contents. Many Linux commands output dozens of lines packed with information. For example, if your Linux machine is running over a dozen Docker containers, you can use grep to zero-in on only the container you are interested in:
meanii ✓ docker ps | grep my-awesome-container
You’ll learn more about the Linux ps command shortly.
You can also save the output of any command to a file by using redirection (>
):
meanii ✓ echo "Linux was created by Linus Torvalds" > bio.txt
The above command will create a new file, or overwrite the contents of an existing file. To append to an existing file, use >>
instead of >
.