Writing Multiple Lines to a File

Learn how to write multiple lines by using cat to redirect the input stream to a file.

We can create files from program output, and we can create a new file with a line of text, but we can also create a new file with multiple lines of text right from the command line without opening a text editor.

The cat command

In Creating and Reading Files, we used the cat command to view the contents of files. The cat command reads the contents of files and displays them to the screen. However, we can also use cat to create new files. Let’s create a simple text file with several lines. Let’s execute the following command:

$ cat > names.txt

After pressing “Enter,” we see a different prompt and a flashing cursor.

The cat command is waiting for input. We type the following lines, pressing “Enter” after each one:

Homer\
Marge\
Bart\
Lisa\
Maggie

After the last line of the file, we press “Enter” one more time, then press “Ctrl+d”. This saves the contents of the file.

We use cat again to view the file to ensure the contents were saved:

$ cat names.txt

Get hands-on with 1200+ tech skills courses.