Insert line sed linux

Linux: Using sed to insert lines before or after a match

The sed utility is a powerful utility for doing text transformations. In this article, I will provide an example of how to insert a line before and after a match using sed, which is a common task for customizing configuration files.

In these examples, we will be dealing with a text file named “text.txt” that contains the following content:

mykey=one anothervalue=two lastvalue=three

Replace a line when match found

The simplest case is replacing an entire line by finding the line that starts with the match.

sed 's/^anothervalue=.*/replace=me/g' test.txt
mykey=one replace=me lastvalue=three

Insert line after match found

Then we have the case where we need to insert a line after the match.

sed '/^anothervalue=.*/a after=me' test.txt
mykey=one anothervalue=two after=me lastvalue=three

Insert a line before match found

Then we have the case where we need to insert a line before the match.

sed '/^anothervalue=.*/i before=me' test.txt
mykey=one before=me anothervalue=two lastvalue=three

Insert multiple lines

And this might have slight variations depending on your POSIX compliance, but if you want to insert multiple lines, you can use ‘\n’ as shown below.

sed '/^anothervalue=.*/i before=me\nbefore2=me2' test.txt
mykey=one before=me before2=me2 anothervalue=two lastvalue=three

Источник

How to Insert a Line after the Match using `sed`?

One of the useful and powerful commands of Linux is the “sed” command. This command is used to perform different types of tasks in Linux, such as insert, update, and delete a particular text or line based on the match. You can insert a text in a string or a file in different ways by using the “sed” command.

How to insert a line after finding a match in a string or a line is shown in this tutorial.

Insert a line in the String

A new line can be inserted after any string value using the “sed” command if the pattern defined in the command matches with any part of the string value.

The following example shows how a new line can be added after a string value if a particular string exists anywhere in the string value.

Example-1: Insert a line in a string after finding a match

The following command will search “inng” in the string, “I like programming”, and a line of text, “Do you like programming?” will be inserted after the string if the searching string exists.

Here, the “&” character is used to insert the line after the string.

The following output shows that “inng” does not exist in the string and no line is inserted after the string.

Читайте также:  Phones that use linux

The following command will search “ing.” in the string, “I like programming” and it exists in the string.

The following output shows that the new line is added after the string.

Insert a line in a File

There are two ways to insert a line after a match is found in a file that is mentioned below. When the “sed” command is used without the “-i option”, then the content of the file will remain unchanged, and the output will show the file content with the inserted newline. You have to use the “-i” option with the “sed” command to insert the new line permanently in the file if the matching pattern exists in the file.

A. Using “a” in the “sed” command

The “a” can be used in the search pattern of the “sed” to append one or more lines in a file after the line where the searching pattern matches or after a particular line number.

B. Using “i” in the “sed” command

The “i” can be used in the search pattern of the “sed” command to insert one or more lines in a file before the line where the searching pattern matches.

Insert line(s) in a file based on the pattern:

Create a tab-delimited text file named products.txt with the following content to show the uses of the above flag in the “sed” command.

products.txt

Example-2: Insert a line after a particular line number using the “a”

The following commands show how a new line can be added, after a particular line number of the products.txt file, based on the pattern used in the “sed” command.

Here, the first command will show the existing content of the file. The “sed” command will append the text, “b01 Baking powder”, after the first two lines of the file. The last command is used to check that the file content is changed or not.

$ sed ‘2 a b01\tBaking powder’ products.txt

The following output will appear after running the above command.

Example-3: Insert a line after the last line using the “a”

The following command shows the way to append a new line after the last line of the file. The first and last command shows the existing content of the file before and after executing the “sed” command. The “$” symbol is used in the pattern of the “sed” command to mention the last line of the file.

$ sed ‘$ a b01\tBaking powder’ products.txt

The following output will appear after running the above command.

Example-4: Insert a line anywhere in the file after matching a pattern using the “a”

The following “sed” command shows how a new line can be added anywhere in the file based on the matching pattern. The pattern used in the “sed” command will search any line starting with “s01”, and add the new string after it. The fourth line of the file starts with “s01”, and the new line will be inserted after that line.

$ sed ‘/^s01.*/a b01\tBaking Powder’ products.txt

The following output will appear after running the command.

The following “sed” command will search any line that ends with “Powder” and insert the new line after it. The third line of the file ends with “Powder”. So, the new line will be inserted after that line.

$ sed ‘/Powder$/a b01\tBaking Powder’ products.txt

The following output will appear after running the above commands.

Читайте также:  Переменные в скрипте линукс

Example-5: Insert multiple lines after the matching pattern using “a”

The following “sed” command shows the way to add multiple lines inside the content of a file based on the matching pattern.

Here, two lines will be added after the third line, according to the pattern.

$ sed ‘/^[a-c]/a b01\tBaking Powder\nb02\tBaking Soda’ products.txt

The following output will appear after running the above commands.

Example-6: Insert a line after matching a pattern using the “I”

$ sed ‘/cream/i b01\tBaking Powder’ products.txt

The following output will appear after running the above commands.

Example-7: Insert a line permanently after the matching pattern using the “-i” option

The following “sed” command shows how to change the content of the file permanently. The “i” option is used with the “sed” command to insert a new line in the file based on the pattern.

$ sed -i ‘/e$/a g01\tGhee’ products.txt

The following output will appear after running the above commands.

Conclusion:

The ways of inserting two or more lines in a file by using the “sed” command with pattern have been shown in this tutorial to help the reader apply this command for inserting lines in the temporarily or permanently based on the pattern.

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 a line at specific line number with sed or awk

I have a script file which I need to modify with another script to insert a text at the 8th line. String to insert: Project_Name=sowstest , into a file called start . I tried to use awk and sed, but my command is getting garbled.

12 Answers 12

sed -i '8i This is Line 8' FILE 

-i does the modification directly to file FILE, no output to stdout, as mentioned in the comments by glenn jackman.

No. -i means «modify the specified file in place». Insert vs. append is achieved with ‘8isomething’ vs. ‘8asomething’, independent from the -i-switch.

This is super useful! Is there anyway for me to insert spaces at the beginning of the line? I noticed sed is not paying attention to initial whitespace.

OS X / macOS / FreeBSD sed

The -i flag works differently on macOS sed than in GNU sed .

Here’s the way to use it on macOS / OS X:

sed -i '' '8i\ 8 This is Line 8' FILE 

. on its own line ends input mode; w writes; q quits. GNU ed has a wq command to save and quit, but old ed’s don’t.

awk -v n=8 -v s="Project_Name=sowstest" 'NR == n ' file > file.new 

@glenn jackman I need to enter #define SERVER@»http://10.35.42.54/ms0.8″ to a particular line. How can I achieve this?

@waLLe, start with the awk info page which has a nice description of how awk works. Here, I have 2 «condition » pairs, the 2nd has no condition which means the action is performed for every record. After you finish reading and you still have questions, let me know.

«file» represents the name of the file that awk is working on. > is the shell redirection symbol so that awk’s output is stored in the file named «file.new».

POSIX sed (and for example OS X’s sed , the sed below) require i to be followed by a backslash and a newline. Also at least OS X’s sed does not include a newline after the inserted text:

$ seq 3|gsed '2i1.5' 1 1.5 2 3 $ seq 3|sed '2i1.5' sed: 1: "2i1.5": command i expects \ followed by text $ seq 3|sed $'2i\\\n1.5' 1 1.52 3 $ seq 3|sed $'2i\\\n1.5\n' 1 1.5 2 3 

To replace a line, you can use the c (change) or s (substitute) commands with a numeric address:

$ seq 3|sed $'2c\\\n1.5\n' 1 1.5 3 $ seq 3|gsed '2c1.5' 1 1.5 3 $ seq 3|sed '2s/.*/1.5/' 1 1.5 3 
$ seq 3|awk 'NR==21' 1 1.5 2 3 $ seq 3|awk '' 1 1.5 3 

awk interprets backslashes in variables passed with -v but not in variables passed using ENVIRON :

$ seq 3|awk -v v='a\ba' '' 1 a 3 $ seq 3|v='a\ba' awk '' 1 a\ba 3 

Both ENVIRON and -v are defined by POSIX.

Читайте также:  Драйвер в линукс запустить

sed -e ‘8iProject_Name=sowstest’ -i start using GNU sed

[root@node23 ~]# for ((i=1; i a_file [root@node23 ~]# cat a_file Line #1 Line #2 Line #3 Line #4 Line #5 Line #6 Line #7 Line #8 Line #9 Line #10 [root@node23 ~]# sed -e '3ixxx inserted line xxx' -i a_file [root@node23 ~]# cat -An a_file 1 Line #1$ 2 Line #2$ 3 xxx inserted line xxx$ 4 Line #3$ 5 Line #4$ 6 Line #5$ 7 Line #6$ 8 Line #7$ 9 Line #8$ 10 Line #9$ 11 Line #10$ [root@node23 ~]# [root@node23 ~]# sed -e '5ixxx (inserted) "line" xxx' -i a_file [root@node23 ~]# cat -n a_file 1 Line #1 2 Line #2 3 xxx inserted line xxx 4 Line #3 5 xxx (inserted) "line" xxx 6 Line #4 7 Line #5 8 Line #6 9 Line #7 10 Line #8 11 Line #9 12 Line #10 [root@node23 ~]# 

Источник

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. $ 

Источник

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