- Bash: добавить текст в файл
- Добавить в файл с помощью оператора перенаправления ( >> )
- Добавить в файл с помощью команды tee
- Выводы
- Linux append text to end of file
- How to redirect the output of the command or data to end of file
- How to add lines to end of file in Linux
- How to append standard output and standard error
- Append text when using sudo
- Conclusion – Append text to end of file on Unix
- How to append text to a file when using sudo command on Linux or Unix
- Method 1: Use tee command
- Bash: append to file with sudo and tee
- Understanding tee command options
- Method 2: Use bash/sh shell
- Conclusion
- How to Append to End of a File in Linux
- Redirect output of command or data to end of file
- Adding lines to end of file
- Adding command data output result to end of file
- Alternative methods
- Using tee command line tool
- Using awk command line tool
- Using sed command line tool
- Append multiple lines to a file
- Conclusion
- How to append text to the end of a file in Linux
- Common Scenarios for appending the text to a file
- Linux Commands to append text to a File
- 1. Append text to the end of a file using redirection operators
- 2. Using cat command with redirection operator (>>)
- 3. Linux echo command with >>
- 4. The tee command with -a option
- 5. Append using”printf” in Linux
- 6. Append the text using awk command
- 7. Save the list of files to another file using >> operator
- Conclusion
Bash: добавить текст в файл
В Bash есть несколько способов добавить текст в файл. Эта статья объясняет некоторые из них.
Чтобы добавить текст в файл, у вас должны быть права на запись в него. В противном случае вы получите сообщение об ошибке в разрешении отказано.
Добавить в файл с помощью оператора перенаправления ( >> )
Перенаправление позволяет захватывать выходные данные команды и отправлять их в качестве входных данных в другую команду или файл. Оператор перенаправления >> добавляет вывод в указанный файл.
Существует ряд команд, которые вы можете использовать для вывода текста на стандартный вывод и перенаправления его в файл, причем наиболее часто используются команды echo и printf .
Чтобы добавить текст в файл, укажите имя файла после оператора перенаправления:
При использовании с параметром -e команда echo интерпретирует экранированные символы обратной косой черты, такие как новая строка n :
Чтобы получить более сложный вывод, используйте команду printf которая позволяет вам указать форматирование вывода:
Другой способ добавить текст в файл — использовать документ Here (Heredoc). Это тип перенаправления, который позволяет передавать команде несколько строк ввода.
Например, вы можете передать содержимое команде cat и добавить его в файл:
Вы можете добавить вывод любой команды в файл. Вот пример с командой date :
При добавлении к файлу с использованием перенаправления будьте осторожны, чтобы не использовать оператор > для перезаписи важного существующего файла.
Добавить в файл с помощью команды tee
tee — это утилита командной строки в Linux, которая считывает из стандартного ввода и записывает как в стандартный вывод, так и в один или несколько файлов одновременно.
По умолчанию команда tee перезаписывает указанный файл. Чтобы добавить вывод в файл, используйте tee с параметром -a ( —append ):
Если вы не хотите, чтобы tee выводил данные на стандартный вывод, перенаправьте его на /dev/null :
Преимущество использования команды tee перед оператором >> заключается в том, что tee позволяет добавлять текст сразу в несколько файлов и записывать в файлы, принадлежащие другим пользователям, вместе с sudo .
Чтобы добавить текст в файл, в который у вас нет прав на запись, добавьте sudo перед tee как показано ниже:
tee получает вывод команды echo , повышает разрешения sudo и записывает в файл.
Чтобы добавить текст в несколько файлов, укажите файлы в качестве аргументов команды tee :
Выводы
В Linux для добавления текста в файл используйте оператор перенаправления >> или команду tee .
Если у вас есть какие-либо вопросы или отзывы, не стесняйтесь оставлять комментарии.
Источник
Linux append text to end of file
You need to use the >> to append text to end of file. It is also useful to redirect and append/add line to end of file on Linux or Unix-like system.
How to redirect the output of the command or data to end of file
The procedure is as follows
- Append text to end of file using echo command:
echo ‘text here’ >> filename - Append command output to end of file:
command-name >> filename
How to add lines to end of file in Linux
The >> is called as appending redirected output. Create the file if does not exists. For example, append some networking command to net.eth0.config.sh script:
echo ‘I=eth0’ >> net.eth0.config.sh
echo ‘ip link set $I up’ >> net.eth0.config.sh
echo ‘ip addr add 10.98.222.5/255.255.255.0 dev $I’ >> net.eth0.config.sh
echo ‘ip route add default via 10.98.222.1’ >> net.eth0.config.sh
You can also add data to other config files. Another option is to run command and append output to a file. Run data command at the terminal and append output to output.txt:
date >> output.txt
Execute ls command and append data to files.txt:
ls >> files.txt
To see files.txt use cat command:
cat files.txt
more files.txt
less files.txt
How to append standard output and standard error
The following sytax allows both the standard output (file descriptor 1) and the standard error output (file descriptor 2) to be appended to the file name. The format for appending standard output and standard error is:
echo ‘text’ &>>filename
command &>>filename
find . type d -name «*.projects» &>> list.txt
This is semantically equivalent to
echo ‘text’ >>fileNameHere 2>&1
command >>fileNameHere 2>&1
date >>data.txt 2>&1
For more info read redirection topic.
Append text when using sudo
Try the tee command:
echo ‘text’ | sudo tee -a my_file.txt
echo ‘104.20.186.5 www.cyberciti.biz’ | sudo tee -a /etc/hosts
Of coruse we can use following syntax to append text to end of file in Linux
sudo sh -c ‘echo my_text >> file1’
sudo — bash -c ‘echo «some data» >> /my/path/to/filename.txt’
The -c option passed to the bash/sh to run command using sudo.
See “how to append text to a file when using sudo command on Linux or Unix” for more info.
Conclusion – Append text to end of file on Unix
To append a new line to a text on Unix or Linux, try:
Источник
How to append text to a file when using sudo command on Linux or Unix
Fig.01: How to append/insert text into a file using sudo on Linux or Unix-like system?
Method 1: Use tee command
The tee command read from standard input (such as keyboard) and write to standard output (such as screen) and files. The syntax is:
echo ‘text’ | sudo tee -a /path/to/file
echo ‘192.168.1.254 router’ | sudo tee -a /etc/hosts
Sample outputs:
This solution is simple and you avoided running bash/sh shell with root privileges. Only append or write part needed root permission.
Bash: append to file with sudo and tee
Want to append text to more than one file while using sudo? Try:
echo ‘data’ | sudo tee -a file1 file2 fil3
Verify that you just appended to a file as sudo with cat command:
cat file1
cat file2
We can append to a file with sudo:
cat my_file.txt | sudo tee -a existing_file.txt > /dev/null
It is a good idea to redirect tee output to /dev/null when appending text. In other words, use >/dev/null when you don’t want tee command to write to the standard output such as screen.
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
Understanding tee command options
- -a OR —append : Append to the given FILEs, do not overwrite
- -i OR —ignore-interrupts : Ignore interrupt signals
- -p : Diagnose errors writing to non pipes
See tee command man page by typing the following man command man tee
Method 2: Use bash/sh shell
The syntax is:
sudo sh -c ‘echo text >> /path/to/file’
sudo — sh -c «echo ‘text foo bar’ >> /path/to/file»
sudo — bash -c ‘echo data >> /path/to/file’
sudo bash -c ‘echo data text >> /path/to/file’
For example:
sudo sh -c ‘echo «192.168.1.254 router» >> /etc/hosts’
You are running bash/sh shell with root privileges and redirection took place in that shell session. However, quoting complex command can be problem. Hence, tee method recommended to all.
Conclusion
As we learned that there are multiple ways to append text to a file using the sudo command.
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Источник
How to Append to End of a File in Linux
In this tutorial, we learn different ways to append text to the end of a file in Linux. You can achieve this using several methods in Linux, but the simplest one is to redirect the command output to the desired filename. Using the >> character you can output result of any command to a text file.
Other ways this can be achieved, is using Linux tools like tee, awk, and sed.
Redirect output of command or data to end of file
Every Unix-based operating system has a concept of “a default place for output to go”. Everyone calls it “standard output”, or “stdout”, pronounced standard out. Your shell (probably bash or zsh) is constantly watching that default output place. When your shell sees new output there, it prints it out on the screen so that you can see it.
We can redirect that output to a file using the >> operator.
The procedure is as follows:
Append text to end of file using echo command:
Append command output to end of file:
Adding lines to end of file
We can add text lines using this redirect character >> or we can write data and command output to a text file. Using this method the file will be created if it doesn’t exist.
Adding command data output result to end of file
You can also add data or run command and append output to the desired file. In this example, we will use date for appending the current date to a file, uname command — which will print out kernel version of the Linux system we are using and lastly ls command which outputs the current directory structure and file list.
You can use any command that can output it’s result to a terminal, which means almost all of the command line tools in Linux.
Alternative methods
Let’s see how to append using tee, awk and sed Linux utility.
Using tee command line tool
Tee command reads the standard input and writes it to both the standard output and one or more files. The command is named after the T-splitter used in plumbing. It breaks the output of a program so that it can be both displayed and saved in a file.
Using awk command line tool
Awk is a utility that enables a programmer to write tiny but effective programs in the form of statements that define text patterns that are to be searched for in each line of a document and the action that is to be taken when a match is found within a line. Awk is mostly used for pattern scanning and processing.
Using sed command line tool
Sed command in Linux stands for stream editor and it can perform lots of functions on a file like searching, find and replace, insertion or deletion. By using sed you can edit files even without opening it, which is a much quicker way to find and replace something in the file.
Append multiple lines to a file
There are several ways to append multiple lines to a file at once.
You can, of course, add lines one by one:
Next variant is to enter new line in terminal:
Another way is to open a file and write lines until you type EOT:
Conclusion
Although there are multiple ways to append the text lines or data and command output to a file, we saw that the easiest way is using >> redirect character. There are ways to append the text to an end of a specific line number in a file, or in the middle of a line using regex, but we will going to cover that in some other article.
Let us know what method to append to the end of the file you think is best down in the comments section.
Источник
How to append text to the end of a file in Linux
If you want to know how to append text to the end of a file in Linux, then you are in the right place. Folks, here we will discuss what are the various ways to append text to a file in Linux.
Table of Contents
Common Scenarios for appending the text to a file
- appending the logs to a log file, generally done by servers.
- saving the output of a command to a file. For example, saving the output of a script to a file for debugging purposes later on.
- copying the content of a file to another file. For example, creating a backup file before making any change to a file.
- concatenating a group of files content to another file. For example, merging a bunch of CSV files to create a new CSV file.
Linux Commands to append text to a File
We use redirection operator (>>) to append data to an existing text file. However, we need to provide the data to be appended to the file. Some of the common commands that are used along with >> operator are cat, echo, print, etc.
Let’s look at some examples to append text to a file in Linux.
1. Append text to the end of a file using redirection operators
Adding the text is possible with the “>” and “>>” operators. These are the output redirection operators. Redirection is sending the output to any file.
There are two types of redirection operator i.e. Input redirection and Output Redirection. “ ” is called Output redirection.
For your understanding, here’s what input redirection looks like.
Here, the input from the file i.e. linux.txt is sent to the tr command through input redirection operator. It will print the characters in uppercase as shown above in the image.
Talking about the Output redirection operator, it is used to send the output of the command to a file. It can be done using any command either cat or echo. Let’s understand it by the following example,
Using “>” operator would send the output of the cat command to the linux.txt file. Further, I have used cat command without “>” operator because here we not going to append text to the end of a file but are just displaying the content of the file.
We will consider the linux.txt file for further examples.
Similarly, “>>” redirection operator is used to append text to the end of a file whereas “>” operator will remove the content in the existing file. I hope the difference is cleared between both of them. Don’t worry, we will discuss this in more detail.
Let’s dive into the ways on how can we append the text in the file using various commands.
2. Using cat command with redirection operator (>>)
The “>>” operator is used to append text to the end of a file that already has content. We’ll use the cat command and append that to our linux.txt file.
Consider we want to append text to the end of a file i.e. linux.txt as shown above. Let’s have a look at the command below:
As shown above, the input text is sent to the file i.e. linux.txt. WE use the cat command once again with the append operator to print the text as shown in the example above.
You can see that the text has been appended at the bottom of the file. Remember while adding the text using “>>” operator through cat command, you’ll be working within the editor mode. To save the text and finish appending, you can press Ctrl+D.
3. Linux echo command with >>
The echo command is used to print the text, print the value of the variable and so on. If you want to have detail knowledge, you can check the tutorial on the echo command in Linux. While using the echo command, you need to add the text within quotations. The output of the echo command will be redirected through the”>>” operator to the file. Let’s have a look at the below command.
You can see that the text “I hope you understood the concept.” is appended at the bottom of the file. You can print the content of the file using cat command. Here also, the text is sent as output to the file through “>>” operator.
4. The tee command with -a option
The tee command is used to read the standard input and writes it to the standard output as well as files too. Using tee command with -a option will not overwrite the content but will append it to the file. Let’s understand through an example.
The text in the linux.txt file is redirected to tee command through “|” operator and is appended to the file linuxfordevices.txt. You can see that all the data is transferred to the new file.
5. Append using”printf” in Linux
You might be thinking why we are using printf in Linux as it is used in C language to print the text. We know that printf is used to display the standard output. Folks, we can also use printf command to append the text using “>>” operator in Linux. Just add the text within quotations and send it to the file as output. Let’s have a look at the command below:
6. Append the text using awk command
The awk command is used to perform the specific action on the text as directed by the program statement. Using the BEGIN keyword with awk command specifies that awk will execute the action as denoted in begin once before any input lines are read.
Therefore, we will provide the command enclosed within the BEGIN as shown below in the example. The command to append the text is provided in the BEGIN section, hence awk command will execute it once it reads the input lines. Let’s have a look at the command below:
You can see that the text “Feel free to reach us” has been appended to the bottom of the linux.txt file as shown above in the image. Use the cat command to print the text of the file.
7. Save the list of files to another file using >> operator
We can also save the list of the files in any directory using ls command with “>>” operator. We have to just use ls command followed by the “>>” operator and the file name where we need to save the output. Let’s have a look at the command below:
Conclusion
In this tutorial, we learned how to use the “>>” operator to append text to the end of a file. We also learned what is the difference between input redirection and output redirection, how to save the list of files and date to any file and so on. I hope that all your concerns are cleared. If face any issues, do let us know in the comment section.
Источник