Linux Commands

How to Create a File with Text in Linux

Working with files is a common chore that Linux professionals have to do. That’s why you need to learn the correct ways to create a text file as a beginner. Although there are multiple ways, the “touch”, “cat”, and “printf” are the most common commands to create the text files in Linux. So, in this quick article, we will list the commands and their examples to create the file in Linux easily without facing any error.

How to Create a File with Text in Linux

While we have the “touch” command and the standard redirect symbol (>) to create one or multiple text files, these options can’t be used to create a new file with some text. To create any text file with some text in it, we can use the “cat”, “echo”, and “printf” commands. Let’s know each one by one.

  1. The Cat Command

The “cat” command creates a new file with the supplied text. For instance, if you wish to create a text file named “my.linux.txt” with the “This is my new file!” text, you can use the “cat” command in the following way:

cat >> my.linux.txt

This is my new file!

 

To end the command, you need to press “Ctrl+C”.

  1. The Echo Command

You can use the “echo” command to create both empty and non-empty text files. For example, let’s create the “newfile.txt” and the text in it.

echo -e 'This is a new file!' >> newfile.txt

 

  1. The Printf Command

The “printf” command is similar to the “echo” command and does the same job but with C-like styling. The “printf” command to create a file with the name “my.newfile.txt” and with the “This is a new file!” text is as follows:

printf "This is a new file!" >> my.newfile.txt

 

  1. Command-Line Text Editors

Command-line text editors like Emacs, Sublime Text, Nano, and Vim make it super easy to create one or more text files with some text in Linux. For instance, you can run the following command, and the system will create and open the text file in the nano editor:

nano my.pass.txt

 

The specific commands and procedures for doing so vary from editor to editor. Thus, you need to check their documentation or online resources to know how to create a file with text in Linux using them.

Conclusion

File handling is quite common while working with Linux. With the provided options, you can quickly create the files with text and enhance your productivity. Linux offers the simplest way to create the text files and quickly add an information from a single command. Please remember that you must use the commands carefully. Otherwise, you may face errors.

About the author

Prateek Jangid

A passionate Linux user for personal and professional reasons, always exploring what is new in the world of Linux and sharing with my readers.