Objective: Use cat
command command to write to a text file.
To write to a file using the cat
command, we can use Here Documents
. A here document is a special-purpose code block. It uses a form of I/O redirection to feed a command list to an interactive program or a command, such as ftp
or cat
.
1 2 3 4 5 |
COMMAND << EOF ... ... ... EOF |
To write the string Hello World
to a file called hello.txt
using here document and cat
, use the following syntax:
1 2 3 |
cat << EOF > hello.txt Hello World EOF |
If instead, you are looking at concatenating or appending file contents to a new file, then here document is not required. To concatenate files in1.txt
and in2.txt
to output.txt
, use the following syntax.
1 |
cat in1.txt in2.txt > output.txt |
Here’s an interview question that I came across. Are you able to guess the output of the following commands?
1 2 3 4 |
cat<<cat>cat <cat> cat cat cat |
You will get the following output:
1 |
<cat> |
The here document is used with the cat
command to write the text <cat>
to a file called cat
and the cat
command is used to print the file cat
to the screen.