Linux add line to file from console

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:

Читайте также:  Warning windows x64 detected pio mode supported on windows x86 only перевод

Источник

How do I insert a line at the top of a text file using the command line?

I want to insert text at the top of an already existing file. How can I achieve this. I tried echo and tee but was not successful.

I was trying to insert repo line at the top of sources.list file from terminal.

I need an one line quick solution, because another answer’s method was known to me already

6 Answers 6

It’s actually quite easy with sed :

sed -i -e ‘1iHere is my new top line\’ filename

1i tells sed to insert the text that follows at line 1 of the file; don’t forget the \ newline at the end so that the existing line 1 is moved to line 2.

In general editing in place with a script is tricky, but you can use echo and cat and then mv

However if you’re playing with sources.list you need to add in some validation and bullet-proofing to detect errors etc because you really don’t want to loose this. But that’s a separate question 🙂

known that prepend is my custom shell:

Use also a relatif path or absolute path , it should work fine :

Update :

if you want a permanent script for this , open nano /etc/bash.bashrc then add this function at the end of file:

Reopen you terminal and enjoy :

And why not use a genuine text editor for that? ed is the standard text editor.

Or, if you want the commands to be more readable:

  • 1 : go to firstline
  • i : insert mode
  • your stuff you want to insert.
  • . : stop inserting, go back to normal mode
  • wq : write and quit, thank you, good bye.

You can use Vim in Ex mode:

1 select 1st line

i insert new line of text

x save and close

There is always the awk option. Replace string variable with your contents. This is not an in-place change though. Personally, I tend to not make in-place changes. This is definitely a personal preference. Two things, -v signifies a variable in awk and variable n is used here to match a line number, effectively NR == 1 . You could use this in any number of ways just by changing the value of n and s .

Not the answer you’re looking for? Browse other questions tagged apt command-line bash or ask your own question.

Linked

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.10.8.40416

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

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.

Читайте также:  Нет оценки индекса производительности windows

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.

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:

Источник

Add words to a text file using a single terminal command (no editors)

I’m new to Linux. I need to edit a .conf file from the open terminal only and not using any text editors. That is, can I add words and sentences to a config file from an open terminal?

Example: command /home/. /file.conf -add ‘abcd’ to the 23rd line and so on. And finally, save it.

Is it possible to search a specific word in that config file and add new text to the next line of that config file using only the command?

5 Answers 5

I usually do this way when I am programming my script to do same what you are asking but programmatically.

Voila! You got it. Important to note >> means adding new line to existing file meanwhile > just simply overwrite everything.

Adding words and sentences to a config file from open terminal can be easily achieved with sed.

inserts at line 23 the text abcd into file file.conf

-i does the modification directly to file file.conf .

If you want to use awk then:

The following adds one line after SearchPattern.

It inserts New Text one line below each line that contains SearchPattern.

Читайте также:  Linux как добавить библиотеку

To add two lines, you can use a \ and enter a newline while typing New Text.

You can also use the printf command.

To add lines to your file

To overwrite the file

  • regex is a regular expression (also known as regex), it defines the search criteria. Regular expressions allow for very customizable searches and the syntax understood by awk is in the manual. In the simplest case — search a string «as it is», character by character — just put a backslash before special characters (see manual for the list of special characters)
  • open inputfile for reading the input lines, clear outputfile and open it for writing the output lines
  • for each line, run the block in braces:
    • if the line matches the regular expression, then output the line with content appended
    • otherwise, output the very same line.

I found a solution to my own question using the ed command

Text can contain 27 lines. You can copy 27 lines from a text file and paste 27 lines to your config file. But I need to run the ed command simultaneously in order to add more text to the same config file.

Not the answer you’re looking for? Browse other questions tagged command-line text editing or ask your own question.

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.10.8.40416

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

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):

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.

Источник

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