Linux append into file

How To Use Cat Command To Append Data To a File on Linux/Unix

I am a new Unix user. I have Debian Linux installed. I need to append text to a file called daily.log. How do I use the cat command to append data to a file?

You can use the cat command to append data or text to a file. The cat command can also append binary data. The main purpose of the cat command is to display data on screen (stdout) or concatenate files under Linux or Unix like operating systems. To append a single line you can use the echo command or printf command command. Let us see how to use the cat command to append data and update files without losing its content.

Tutorial details
Difficulty level Easy
Root privileges No
Requirements cat on Linux or Unix
Est. reading time 2 mintues

How To Use Cat Command To Append Data To a File on Linux/Unix

Redirection symbol is as follows for appending data to a file:

Syntax

Examples

Create a text file called foo.txt, type:

To save the changes press CTRL-d i.e. press and hold CTRL and press d. Create another text file called bar.txt as follows:

Display both files on the screen, enter:

To append a contains of bar.txt to to foo.txt, enter:

To append a ‘Use unix or die’ text to foo.txt file, enter:

  • 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

Fig.01: Using the cat and echo command to append a text to a file.

Append text to a file when using sudo command

We can use the echo command or printf command to append data to a file called sales.txt in the current directory:

Want to append to a file? Try:
cat filename | sudo tee -a foo_file.txt
In this example append data using the following syntax:
sudo sh -c ‘echo «192.168.1.253 wireless-router» >> /etc/hosts’
Verify it:
cat /etc/hosts

Summing up

We explained various Linux and Unix commands that one could use to append data to a file. Although I tested all examples on Bash running on macOS and Linux desktop, these examples should work with other shells, too, such as:

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Category List of Unix and Linux commands
Documentation help • mandb • man • pinfo
Disk space analyzers df • duf • ncdu • pydf
File Management cat • cp • less • mkdir • more • tree
Firewall Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04
Linux Desktop Apps Skype • Spotify • VLC 3
Modern utilities bat • exa
Network Utilities NetHogs • dig • host • ip • nmap
OpenVPN CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04
Package Manager apk • apt
Processes Management bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop
Searching ag • grep • whereis • which
Shell builtins compgen • echo • printf
Text processing cut • rev
User Information groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w
WireGuard VPN Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04

Comments on this entry are closed.

when i execute two commands like echo $val(nn) > t.txt and awk -f throughput.awk wpan.tr >t.txt
i want the file t.txt to have two columns side by side leaving a tab or space in between. but i m getting output like this

pls help in this regard…thanks

I’m not sure I understood your query. To merge corresponding or subsequent lines of files try paste command.

Источник

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

  1. -a OR —append : Append to the given FILEs, do not overwrite
  2. -i OR —ignore-interrupts : Ignore interrupt signals
  3. -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

Источник

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

  1. Append text to end of file using echo command:
    echo ‘text here’ >> filename
  2. 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:

Источник

Your Own Linux.

Linux How To’s | Bash Scripting | Python

Sunday, 19 April 2015

Sed Command in Linux — Append and Insert Lines to a File

This is the second article of the «Super sed ‘ Series», in which we will learn how to append and insert lines to a file using line numbers and regular expressions. In the previous article in the series, we learned to print lines in a file using sed command.

Before we directly jump to the main content, every learner should know what sed is. Here is the brief introduction of the Super sed :

  • sed stand for Stream EDitor and it being based on the ed editor, it borrows most of the commands from the ed . It was developed by Lee E. McMahon of Bell Labs.
  • sed offers large range of text transformations that include printing lines, deleting lines, editing line in-place, search and replace, appending and inserting lines, etc.
  • sed is useful whenever you need to perform common editing operations on multiple lines without using ‘vi’ editor.
  • Whenever sed is executed on an input file or on the contents from stdin, sed reads the file line-by-line and after removing the trailing newline, places it in the «Pattern space», where the commands are executed on them after conditions (as in case of regex matching) are verified, and then printed on the stdout.

sed — Appending Lines to a File

For our better understanding, let us have a file sedtest.txt with contents as follows:

1. Append a line after ‘N’th line

This will add a line after ‘N’th line in the FILE.txt .

Example:
To append a line #This is just a commented line after 1st line,

While, to append a line after last line,

If you run above commands and inspect the file sedtest.txt , you would find that, the original contents of that file would not change. In case you wish to append lines in the file and save the changes (i.e. edit the file in place), you will have to use the option -i .

Lets check it for the latest command we have run to append lines after the last line of the file. Has it made any changes to the file?

No, the original file remains the same. But, I wanted to save the changes to the file. So, I should have used the option -i .

Yes, now changes are written to the file. Just remember this.

2. Append Line using Regular Expression/Pattern

This will append the line after the line where pattern match is found.

sed — Inserting Lines in a File

1. Insert line using the Line number

This will insert the line before the line at line number ‘N’.

While, to insert a line before last line,

2. Insert lines using Regular expression

This will insert the line before every line where pattern match is found.

That’s all about the second article on sed command. More articles on sed are coming soon. So, stay tuned. Of course, do not forget to share your feedback in the comment section below.

Источник

Читайте также:  Смартфон линукс вместо андроид
Оцените статью