Linux insert line to file

How to insert text after a certain string in a file?

please edit you Q and show the input and the output lines. Because you Q is unclear. You could also do echo «Hello World [option]» >> file.txt , but it doesn’t make sense.

I edited the question to provide more information for reference but the accepted answer was what I was trying to accomplish

If you just want to edit a config file this is the best solution I found: unix.stackexchange.com/a/78076/20661

4 Answers 4

Append line after match

Insert line before match

Additionally you can take backup and edit input file in-place using -i.bkp option to sed

The above code will append/insert the line for every single match. If you want to append/insert the line for the first match only, you can prepend 0, to the commands: sed ‘0,/\[option\]/a Hello World’ input or sed ‘0,/\[option\]/i Hello World’ input

If the appended string is a multiline text u can save it to a file (e.g.: snippet.txt) and inject this file after the pattern using: sed -i ‘/pattern/ r snippet.txt’ filename

Yes, it is possible with sed :

sed '/pattern/a some text here' filename 
$ cat test foo bar option baz $ sed '/option/a insert text here' test foo bar option insert text here baz $ 

Keep in mind that some characters can not be included literally so one has to use escape sequences (they begin with a backslash) e.g. to print a literal backslash one has to write \\ .

It’s actually the same with sed but in addition each embedded newline in the text has to be preceded by a backslash:

sed '/PATTERN/a\ add one line\ \\and one more' infile 

For more details on escape sequences consult the manual.

Also, to address some of the comments: the above commands DO NOT edit the file in place, they just print the result to the standard output. To actually modify the input file you would either use the -i switch if your awk / sed support it (consult the manual) or redirect to a temporary file then overwrite the original e.g.

cmd infile > outfile mv outfile infile 

Or use ed / ex which can edit the files in-place on all platforms:

Remember: with ed / sed / ex , a appends and i inserts; with awk , to insert, move the 1 to the end.

Читайте также:  Xrandr установка разрешения astra linux

Источник

How to append a line to a file in bash

Sometimes we need to work with a file for programming purposes, and the new line requires to add at the end of the file. This appending task can be done by using ‘echo‘ and ‘tee‘ commands. Using ‘>>’ with ‘echo’ command appends a line to a file. Another way is to use ‘echo,’ pipe(|), and ‘tee’ commands to add content to a file. How these commands can be used in the bash script are shown in this article.

Create a text file named books.txt with the following content to do the examples shown in the next part of this article.

Example-1: Append line to the file using ‘echo’ command and ‘>>’ symbol

In the following script, an existing file, books.txt is assigned to the variable, filename, and a string value will be taken as input from the user to add at the end of the file. If the input value is not empty, then the ‘echo’ command will append the value into the books.txt file by using ‘>>’ symbol.

# Define the filename
filename = ‘books.txt’

# Type the text that you want to append
read -p «Enter the text that you want to append:» newtext

# Check the new text is empty or not
if [ » $newtext » ! = «» ] ; then
# Append the text by using ‘>>’ symbol
echo $newtext >> $filename
fi

Learning JQuery‘ is taken as a new text value in the output that is appended at the end of the file.

Example-2: Append line to the file using ‘printf’ command and ‘>>’ symbol

>>’ symbol can be used with the ‘printf’ command to append formatted content to a file. Like the previous example, the filename and the string values are assigned to the variables, filename, and newtext. Next, ‘printf’ command will redirect the value of newtext with other text into the end of the books.txt file.

# Define the filename
filename = ‘books.txt’

# Type the text that you want to append
read -p «Enter the text that you want to append:» newtext

# Check the new text is empty or not
if [ » $newtext » ! = «» ] ; then
# Append the text by using ‘>>’ symbol
printf «Appended text is: %s \n » » $newtext » >> $filename
fi

Website by WordPress‘ is taken as a new text value in the output that is appended at the end of the file.

Example-3: Append line to the file using `tee` command

tee’ is another useful command to append any string into a file. In the following script, the filename and the new text values are assigned like the previous examples. If the text value is not empty, then the ‘echo’ command will send the value to the ‘tee’ command using ‘|’ symbol. ‘-a’ option is used with ‘tee’ command here to append the received input value to the file books.txt. ‘/dev/null’ is used in the script to prevent showing the output in the terminal.

Читайте также:  Каким приложением занят порт linux

# Define the filename
filename = ‘books.txt’

# Type the text that you want to append
read -p «Enter the text that you want to append:» newtext

# Check the new text is empty or not
if [ $newtext ! = «» ] ; then
# Append the text by using `tee` command
echo $newtext | tee -a $filename > / dev / null
fi

Learning CSS3‘ is taken as a new text value in the output that is appended at the end of the file.

Conclusion:

Three different ways are shown in this article to append text at the end of a file using a bash script.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.

Источник

Insert lines in a file starting from a specific line

When using sed -i does this rewrite the entire file but with sed ‘s replacements or is this similar to just opening up the file in a text editor and manually inserting the strings? I ask because I need to do this with a big file and having to write that much over and over again will take forever and wear out my SSDs and HDDs quicker.

What exactly do you expect a text editor to do physically if you open up a file, manually insert the strings and save it?

Or anoter one example with the sed :

echo -e "line 1\nline 2\nline 3\nline 4" > /tmp/test.txt cat /tmp/test.txt line 1 line 2 line 3 line 4 

Add a new line into the test.txt file:

sed -i '2 a line 2.5' /tmp/test.txt # sed for in-place editing (-i) of the file: 'LINE_NUMBER a-ppend TEXT_TO_ADD' cat /tmp/test.txt line 1 line 2 line 2.5 line 3 line 4 

This is definitely a case where you want to use something like sed (or awk or perl ) rather than readling one line at a time in a shell loop. This is not the sort of thing the shell does well or efficiently.

You might find it handy to write a reusable function. Here’s a simple one, though it won’t work on fully-arbitrary text (slashes or regular expression metacharacters will confuse things):

function insertAfter # file line newText < local file="$1" line="$2" newText="$3" sed -i -e "/^$line$/a"$'\\\n'"$newText"$'\n' "$file" >
$ cat foo.txt Now is the time for all good men to come to the aid of their party. The quick brown fox jumps over a lazy dog. $ insertAfter foo.txt \ "Now is the time for all good men to come to the aid of their party." \ "The previous line is missing 'bjkquvxz.'" $ cat foo.txt Now is the time for all good men to come to the aid of their party. The previous line is missing 'bjkquvxz.' The quick brown fox jumps over a lazy dog. $ 

Источник

Читайте также:  Linux veeam agent backup repository

Command to append line to a text file without opening an editor

You can append a line of text to a file by using the >> operator:

echo "hello world" >> my_file.txt 
echo "alias list='ls -cl --group-directories-first'" >> config.fish 

I use echo myself, but be careful, if you only specify one > then the file will truncate, not append. for a safer command you can use sed: sed -i ‘$a hello world’ filename

explanation: -i will update the file (otherwise it will just print the result to stdout), $ is regex that will match the end of the file, and a appends the following text to filename.

echo «hello world» >> my_file.txt does not create a new last line with HW , but add it to the string of the last line.

Maybe «Hello World» @7wp 🙂 It’s echo that adds the line break (making it a line as opposed to just a bunch of characters). You can switch off the line break at the end with -n .

Adding to Stefano’s answer, you can also use cat :

$ cat >> config.fish alias list='ls -cl --group-directories-first' > EOF 

I often use this method but recently got caught when I pasted in a text that included some (escape) codes. It didn’t complain but when I checked the file there were chunks of pasted text missing. So use it with care!

@elmclose Sorry, which method? They work differently with respect to metacharacters. I think the second one doesn’t do anything with them, though there might be a few exceptions.

I meant EOF method. Very convenient and useful when you type or paste in readable text. But codes in my text confused the process. The file was a bash script that kept failing. Took me a while before I discovered what had happened.

There’s plenty of methods of appending to file without opening text editors, particularly via multiple available text processing utilities in Ubuntu. In general, anything that allows us to perform open() syscall with O_APPEND flag added, can be used to append to a file.

    GNU version of dd utility can append data to file with conv=notrunc oflag=append

printf "\nalias list='ls -cl --group-directories-first'\n" | dd conv=notrunc oflag=append bs=1 of=config.fish 
sed -i '$a alias list='"'"'ls -cl --group-directories-first'"'" config.fish 
 #!/usr/bin/env python3 # read bytes from stdin, append to specified file import sys with open(sys.argv[1],'ab') as f: f.write(sys.stdin.buffer.read()) 

See also:

Источник

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