- Write to a File From the Shell
- Writing to a File Using Redirection Operators
- The Regular Output Operator ( > )
- The Append Operator ( >> )
- Use Here Document (Heredoc) Redirection
- Advanced Editing with Sed
- Find and Replace
- Select Lines
- Delete Lines
- Conclusion
- More Information
- Writing Text to File Using Linux Cat Command
- 1. Overview
- 2. The cat Command
- 3. The Syntax
- 4. Making cat Read From stdin
- 5. Writing to a File Using cat
- 6. Appending Text to File Using cat
- 7. Here Document
- 8. Conclusion
Write to a File From the Shell
Estamos traduciendo nuestros guías y tutoriales al Español. Es posible que usted esté viendo una traducción generada automáticamente. Estamos trabajando con traductores profesionales para verificar las traducciones de nuestro sitio web. Este proyecto es un trabajo en curso.
When working from the command line, it can be convenient to write to files without the need to open a text editor like Nano, or Vim. There are some handy Linux operators and commands to make writing to files simple to accomplish. This guide shows you how to use key operators and commands to write to files from the shell. These commands work with Bash, Zsh shells, and several other Unix shells.
Writing to a File Using Redirection Operators
The Regular Output Operator ( > )
You can use the regular output operator ( > ) to write text to a file. If it does not exist already, it creates the file.
Follow the steps below to learn how to use the > operator:
- Issue the following command to write the text to a file. The command creates the file in the process.
echo "This text is written to a file." > example-single-arrow.txt
cat example-single-arrow.txt
This text is written to a file.
echo "This text overwrites the file's contents." > example-single-arrow.txt cat example-single-arrow.txt
This text overwrites the file's contents.
The Append Operator ( >> )
The append operator ( >> ) works much like the regular output operator. It writes text you pass to it to a designated file, creating the file if it does not already exist. However, the important distinction is that >> appends contents to an already existing file rather than overwriting them.
Follow the steps below to learn how to use the >> operator:
- Write text to a new file, creating the file in the process.
echo "This text is written to a file." >> example-double-arrow.txt cat example-double-arrow.txt
This text is written to a file.
echo "This text is appended to the file." >> example-double-arrow.txt cat example-double-arrow.txt
This text is written to a file. This text is appended to the file.
Use Here Document (Heredoc) Redirection
Here Document (Heredoc) redirection allows you to pass multiline input to a shell command. This method helps you bypass the need to issue multiple commands when writing multiple lines to a file.
Below is an example of a heredoc redirect that writes multiple lines to a file.
Once the lines have been given the closing delimiter, they are redirected to the command given before the operator.
These lines are written to a new file.
You can also use the Heredoc redirect to append lines to an existing file by using the >> operator after the cat command instead of the > operator:
The above command defines different delimiter text, uses a shell variable, and the date command. In this case, the variable and the command get evaluated before the content is written to the file.
These lines are written to a new file. These additional lines to the file in /home/example-user were added on 06/30/2021.
You can also prevent the Heredoc redirect from evaluating variables and commands by using quotes (single or double) around your delimiter definition.
In this case, the example-heredoc.txt file contains the text of the unevaluated commands.
Advanced Editing with Sed
Sed is a command-line stream editor that gives you access to advanced file writing features while still working from the shell.
The operators in the sections above give you ways to write to files and append content to them. Sed can write to files, but also provides powerful tools for editing and manipulating files.
Find and Replace
One of the most common uses for Sed is to replace text in a file. The example below edits the example-heredoc.txt file created in the Heredoc section above.
sed -i 's/$PWD/$HOME/g' example-heredoc.txt
The quoted portion of the command is the Sed expression. It tells Sed to substitute ( s ) occurrences of $PWD with $HOME . The g tells Sed to replace all instances on each line.
The -i option has Sed write the changes in place, meaning directly to the file. Without this option, Sed simply outputs the results. Omitting the -i option can be useful to try out Sed commands before committing to them. You can also provide a backup extension with the -i option to have Sed back your file up before writing changes.
sed -i'.bak' 's/$PWD/$HOME/g' example-heredoc.txt
Select Lines
You can also use Sed to select lines, which you can do by line number or by line contents.
For instance, the command below selects and outputs the third line of the file.
sed -n '3p' example-heredoc.txt
without evaluating either.
The p in the Sed expression tells Sed to print the line. Normally, Sed outputs all lines from the file, so the -n option is necessary here to have Sed only output the selected line.
You can select a range of lines by separating the beginning and ending line numbers with a comma.
sed -n '1,2p' example-heredoc.txt
These lines include the $HOME variable and the $(date '+%m/%d/%Y') command
Selecting and outputting a line based on the text it contains works similarly.
sed -n '/date/p' example-heredoc.txt
Finally, Sed also accepts multiple expressions, using the -e option before each expression.
sed -n -e '1p' -e '/date/p' example-heredoc.txt
These lines include the $HOME variable and the $(date '+%m/%d/%Y') command
Delete Lines
Sed can also delete lines for you. The syntax for determining which lines to delete is the same used for selecting lines. Replace the p portion of the command with d to have Sed delete the matching lines.
The following example combines a substitute expression with a delete expression and writes the results directly to the file.
sed -i -e 's/either/it/g' -e '/date/d' example-heredoc.txt
Conclusion
With the redirect operators and Sed commands above, you should be able to write to files directly right from the command line. The operators and commands used in this guide are also helpful when you need to work with files in Bash scripts and other shell scripts. If you are interested in learning more about Bash scripts, check out our series of guides on Bash scripting.
More Information
You may wish to consult the following resources for additional information on this topic. While these are provided in the hope that they will be useful, please note that we cannot vouch for the accuracy or timeliness of externally hosted materials.
This page was originally published on Thursday, August 12, 2021.
Writing Text to File Using Linux Cat Command
The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.
To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.
Connect your cluster and start monitoring your K8s costs right away:
1. Overview
In this tutorial, we’ll look at how to write text into a file using the Linux cat command.
2. The cat Command
The cat command is a utility command in Linux. One of its most common usages is to print the content of a file onto the standard output stream. Other than that, the cat command also allows us to write some texts into a file.
3. The Syntax
Let’s take a look at the general syntax of the cat command:
First, OPTION is a list of flags we can apply to modify the command’s printing behavior, whereas FILE is a list of files we want the command to read.
From the documentation, we can see that if no value is passed for the FILE argument, the cat command will read from standard input. Similarly, it will behave the same when a dash “-” value is passed for the FILE argument. In combination with the Linux redirection operators, we can make the cat command listen to the standard input stream and redirect the content to a file.
4. Making cat Read From stdin
Let’s execute the cat command:
After we enter the command, we’ll see that the command will not return anything. This is because the cat command is now listening to the standard input.
Let’s try to enter some texts into the terminal:
cat This is a new line This is a new line
We can see that whatever texts we’ve entered into the standard input stream will be echoed to the output stream by the cat command. Once we are done, we can terminate the command by pressing CTRL+D.
5. Writing to a File Using cat
To write to a file, we’ll make cat command listen to the input stream and then redirect the output of cat command into a file using the Linux redirection operators “>”.
Concretely, to write into a file using cat command, we enter this command into our terminal:
We’ll see that once again the terminal is waiting for our input.
However, this time it won’t echo the texts we’ve entered. This is because we’ve instructed the command to redirect the output to the file readme.txt instead of the standard output stream.
Let’s enter some texts into the terminal, followed by CTRL+D to terminate the command:
cat > readme.txt This is a readme file. This is a new line.
The file readme.txt will now contain the two lines we’ve entered.
To verify our result, we can use the cat command once again:
cat readme.txt This is a readme file. This is a new line.
Voila! We’ve written into a file using the cat command.
6. Appending Text to File Using cat
One thing we should note in the previous example is that it’ll always overwrite the file readme.txt.
If we want to append to an existing file, we can use the “>>” operator:
cat >> readme.txt This is an appended line.
To verify that the last command has appended the file, we check the content of the file:
cat readme.txt This is a readme file. This is a new line. This is an appended line.
There we have it. The line we enter is appended to the end of the file instead of replacing the entire document.
7. Here Document
It is also worth noting that the here document syntax can be used with the cat command:
EOF is a token that tells the cat command to terminate when it sees such a token in the subsequent lines.
The token can be any other value as long as it is distinct enough that it won’t appear in the input stream literal. Do note that both the starting and ending EOF tokens will not show up in the readme.txt file.
8. Conclusion
In this article, we’ve taken a look at the general syntax of the cat command.
We’ve also shown how we can make cat command listen from standard input stream instead of a specific file.
Finally, we’ve demonstrated how to write or append to a file, using the cat command along with the Linux redirection operators.