Linux write text file

Writing to Files Using cat Command on Linux

The cat command is a Unix tool used for manipulating and displaying file contents. The command gets its name from the word «concatenate» because it has, among other things, the ability to concatenate files.

In this article, we’ll go through a few easy ways to use this command to write text to a file with examples. Using cat is very straightforward, so no prior programming or Unix experience is needed to follow along.

cat Command Basics

Starting, we’ll just sum up the basics of the cat command to help you out if you’ve never used it before or need a brief overview.

Syntax

The syntax looks like this:

To quickly look up the syntax or command options, run cat with the help option:

Or, you can use the manual pages:

These commands should display the following list of options:

 -A, --show-all equivalent to -vET -b, --number-nonblank number nonempty output lines, overrides -n -e equivalent to -vE -E, --show-ends display $ at end of each line -n, --number number all output lines -s, --squeeze-blank suppress repeated empty output lines -t equivalent to -vT -T, --show-tabs display TAB characters as ^I -u (ignored) -v, --show-nonprinting use ^ and M- notation, except for LFD and TAB --help display this help and exit --version output version information and exit 

Displaying File Contents on the Standard Output

To print the contents of a file to the standard output just name the file you want to display:

If the file is in a different directory, you’ll have to navigate to it:

We’ll be expecting to see the contents of this file, printed to the standard output, in this case — the terminal:

This is the most common use of the cat command since it makes it easy to peek into the contents of a file without opening a text editor.

Writing Text to a File Using cat

To redirect the output of the cat command from the standard output to a file, we can use the output redirection operator > :

This will overwrite the contents of filename2 with the contents of filename1 , so make sure that filename2 doesn’t contain anything you would mind losing. Now, filename2 contains:

The output redirection operator will redirect the output of any command we call. For example, let’s try it out with the pwd command, which prints the name of the current working directory:

If we take a look at the testfile now:

It contains the current working directory’s path:

If the file you are redirecting to doesn’t exist, a file by that name will be created:

$ cat filename1 > newfilename 

Concatenating Files with cat

Concatenating multiple files using cat is simple — just list the files in the desired order:

Читайте также:  Skype share screens linux

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

$ cat filename1 filename2 > outputfile $ cat outputfile 

This takes the filename1 and filename2 files, concatenates them, and outputs the into a new outputfile :

Content of filename1! Content of filename2! 

Standard Input Between Files

When the name of the input file isn’t listed, cat starts reading from the standard input until it reaches EOF (end-of-file). The end-of-file signal is sent by the ctrl+d command line shortcut:

$ cat > outputfile Hello World $ cat outputfile 

We can even add text from the standard input in between files we wish to concatenate by using — to indicate where we expect standard input. If we have files such as filename1 , filename2 , and filename3 , and we want some text from the standard input in between filename1 and filename2 , we would write:

 $ cat filename1 - filename2 filename3 > output Text from standard input! $ cat output 

Checking output , we’ll see something along the lines of:

Content of filename1! Text from standard input! Content of filename2! Content of filename3! 

Appending Files with cat

In the previous examples, using the redirection operator discarded the previous contents of the output file. What if we want to append the new content to the old content? To append files we use the >> operator:

$ cat filename1 filename2 >> output $ cat output 

And that should result in:

Original output file contents. Content of filename1! Content of filename2! 

Concatenating Contents of all Files Directory with cat

To concatenate all contents of all files in a directory, we use the wildcard * :

To concatenate all contents of all files in the current working directory, we’d use:

* can also be used to concatenate all files with the same extension:

Enumerating Line Numbers

Enumeration of all lines of output is done with the -n option:

$ cat -n filename1 filename2 filename3 > output $ cat output 

Which would write something along the lines of:

 1 Content of filename1! 2 Content of filename2! 3 Content of filename3! 

Write $ at the End of Every Line

The -E option marks the end of every line in the file with the $ character:

$ cat -E filename1 filename2 filename3 > output $ cat output 

Sorting Lines of Concatenated Files by Piping

This one is a bit of a cheat. The cat command can’t sort, but we can use piping to achieve that. The pipe command ( | ) is used to turn the output of one command into the input of another. To sort the lines of a file, we’ll use both cat and another command, called sort :

$ cat filename2 filename3 filename1 | sort > output $ cat output 
Content of filename1! Content of filename2! Content of filename3! 

Conclusion

Cat is a simple, yet powerful Unix tool that comes pre-installed on most systems. It can be used on its own or in combination with other commands using pipes. Originally made by Ken Thompson and Dennis Ritchie in 1971, cat ‘s easy to use and intuitive functionalities stand the test of time.

In this article, we’ve explored some of the possibilities of using the cat command to write text to files, check contents, concatenate and append files as well as enumerate lines and sort them.

Читайте также:  Single mode linux centos

Источник

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.

Читайте также:  Обновление всех приложений linux

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.

Источник

Оцените статью
Adblock
detector