Adding line to file linux

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.

Читайте также:  Utorrent для windows android

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.

Источник

How to append multiple lines to a file

I am writing a bash script to look for a file if it doesn’t exist then create it and append this to it:

So «line then new line ‘tab’ then text» I think its a sensitive format. I know you can do this:

But it seems weird since its two lines. Is there a way to append that in this format:

10 Answers 10

If sudo (other user privileges) is needed to write to the file, use this:

Or, if it’s a literal tab that you want (rather than the four spaces in your question):

Читайте также:  Calculate linux server gui

You can achieve the same effect with echo , but exactly how varies from implementation to implementation, whereas printf is constant.

Another approach is to use tee

A few choice lines from tee ‘s man page:

The tee utility copies standard input to standard output, making a copy in zero or more files.

-a — Append the output to the files rather than overwriting them.

Here is an example to append multiple lines in a file:

SED can append a line to the end of a file like so:

sed -i ‘$ a text to be inserted’ fileName.file
$ selects end of file, the a tells it to append, and after this comes the text that is to be inserted. Then of course the file name.

Does this approach have any added benefit than other solutions?
Yes, this approach has the added benefit of appending to any files return in a search, such as this: find . -name «*.html» -exec sed -i ‘$ a ‘ <> \;

I used the above example to insert the ending html tag that was missing on every html page within a number of directories.

Источник

How to insert a text at the beginning of a file?

So far I’ve been able to find out how to add a line at the beginning of a file but that’s not exactly what I want. I’ll show it with an example:

File content

Result

It’s similar but I don’t want to create any new line with it.

I would like to do this with sed if possible.

16 Answers 16

sed can operate on an address:

What is this magical 1s you see on every answer here? Line addressing!.

If you want to add a line at the beginning of a file, you need to add \n at the end of the string in the best solution above.

The best solution will add the string, but with the string, it will not add a line at the end of a file.

If the file is only one line, you can use:

If it’s more than one line. one of:

I’ve included the latter so that you know how to do ranges of lines. Both of these «replace» the start line marker on their affected lines with the text you want to insert. You can also (assuming your sed is modern enough) use:

to do in-place editing.

Unfortunately, command substitution will remove newlines at the end of file. So as to keep them one can use:

Neither grouping nor command substitution is needed.

To insert just a newline:

You can use cat —

To add a line to the top of the file:

This will work even is the string containing forward slash «/»

Note that on OS X, sed -i

file , fails. However, if you provide a backup extension, sed -i old

file , then file is modified in place while file.old is created. You can then delete file.old in your script.

There is a very easy way:

Hi with carriage return:

PROBLEM: tag a file, at the top of the file, with the base name of the parent directory.

tag the top of file1 with Programming .

SOLUTION 1 — non-empty files:

1s places the text at line 1 of the file.

SOLUTION 2 — empty or non-empty files:

Note that the — in the cat command is required (reads standard input: see man cat for more information). Here, I believe, it’s needed to take the output of the printf statement (to STDIN), and cat that and the file to temp . See also the explanation at the bottom of http://www.linfo.org/cat.html.

Читайте также:  Microsoft windows perfnet что это

I also added -f to the mv command, to avoid being asked for confirmations when overwriting files.

To recurse over a directory:

Note also that this will break over paths with spaces; there are solutions, elsewhere (e.g. file globbing, or find . -type f . -type solutions) for those.

ADDENDUM: Re: my last comment, this script will allow you to recurse over directories with spaces in the paths:

Источник

Appending a line to a file only if it does not already exist

I need to add the following line to the end of a config file:

to a file called lighttpd.conf

I am looking into using sed to do this, but I can’t work out how.

How would I only insert it if the line doesn’t already exist?

22 Answers 22

Just keep it simple 🙂

grep + echo should suffice:

Edit: incorporated @cerin and @thijs-wouters suggestions.

This would be a clean, readable and reusable solution using grep and echo to add a line to a file only if it doesn’t already exist:

If you need to match the whole line use grep -xqF

Add -s to ignore errors when the file does not exist, creating a new file with just that line.

Using sed, the simplest syntax:

This would replace the parameter if it exists, else would add it to the bottom of the file.

Use the -i option if you want to edit the file in-place.

If you want to accept and keep white spaces, and in addition to remove the comment, if the line already exists, but is commented out, write:

Please note that neither option nor value must contain a slash / , or you will have to escape it to \/ .

To use bash-variables $option and $value , you could write:

The bash expression $

Note: i Just trapped into a problem. In bash you may quote «$

All combined in a bash function:

Explanation:

  • /^\(option=\).*/ : Match lines that start with option= and ( .* ) ignore everything after the = . The \( … \) encloses the part we will reuse as \1 later.
  • /^#\?(\s*'»$
  • /^\(option=\).*/ <…>: If matches a line /…/ , then execute the next command. Command to execute is not a single command, but a block <…>.
  • s//…/ : Search and replace. Since the search term is empty // , it applies to the last match, which was /^\(option=\).*/ .
  • s//\1value/: Replace the last match with everything in (…) , referenced by \1 and the text value`
  • :a;n;ba;q : Set label a , then read next line n , then branch b (or goto) back to label a , that means: read all lines up to the end of file, so after the first match, just fetch all following lines without further processing. Then q quit and therefore ignore everything else.
  • $aoption=value : At the end of file $ , append a the text option=value

More information on sed and a command overview is on my blog:

Источник

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