How to Create a File with Content in Ubuntu Command Line
This article outlines the most efficient methods for creating files with specific content directly from the Ubuntu terminal. It covers using echo, cat, and printf commands to write single or multiple lines of text into new files. By mastering these commands, you can automate file creation and manage data quickly without launching a graphical text editor.
Using the Echo Command
The echo command is the quickest way to create a file
with a single line of text. Open your terminal and type the following
command, replacing the text and filename as needed:
echo "This is the content" > filename.txtThe > operator creates the file if it does not exist
and writes the text into it. If the file already exists, this command
will overwrite its previous content.
Using Cat with Heredoc
For files requiring multiple lines of content, use the
cat command with a heredoc. This allows you to type
multiple lines before saving the file. Enter the following command:
cat > filename.txtType your desired content line by line. When you are finished, press
Ctrl + D on a new line to save and exit. The terminal will
return to the prompt, and your file will contain all the entered
text.
Using the Printf Command
The printf command offers more control over formatting
than echo. It is useful when you need to include specific escape
characters like newlines or tabs. Use it similarly to echo:
printf "Line 1\nLine 2\n" > filename.txtThis command creates the file and writes “Line 1” and “Line 2” on separate lines.
Appending Content to Existing Files
If you want to add content to a file without deleting what is already
there, use the >> operator instead of
>. This works with both echo and printf:
echo "New line of text" >> filename.txtThis command adds the new text to the end of the existing file, preserving the original content.