Sed linux add line

Содержание
  1. How to Insert a Line after the Match using `sed`?
  2. Insert a line in the String
  3. Example-1: Insert a line in a string after finding a match
  4. Insert a line in a File
  5. Example-2: Insert a line after a particular line number using the “a”
  6. Example-3: Insert a line after the last line using the “a”
  7. Example-4: Insert a line anywhere in the file after matching a pattern using the “a”
  8. Example-5: Insert multiple lines after the matching pattern using “a”
  9. Example-6: Insert a line after matching a pattern using the “I”
  10. Example-7: Insert a line permanently after the matching pattern using the “-i” option
  11. Conclusion:
  12. About the author
  13. Fahmida Yesmin
  14. Unix Sed Tutorial: Append, Insert, Replace, and Count File Lines
  15. Append Lines Using Sed Command
  16. Sed Append Example 1. Add a line after the 3rd line of the file.
  17. Sed Append Example 2. Append a line after every line matching the pattern
  18. Sed Append Example 3. Append a line at the end of the file
  19. Insert Lines Using Sed Command
  20. Sed Insert Example 1. Add a line before the 4th line of the line.
  21. Sed Insert Example 2. Insert a line before every line with the pattern
  22. Sed Insert Example 3. Insert a line before the last line of the file.
  23. Replace Lines Using Sed Command
  24. Sed Replace Example 1. Replace a first line of the file
  25. Sed Replace Example 2. Replace a line which matches the pattern
  26. Sed Replace Example 3. Replace the last line of the file
  27. Print Line Numbers Using Sed Command
  28. Sed Line Number Example 1. Find the line number which contains the pattern
  29. Sed Line Number Example 2. Printing Range of line numbers
  30. Sed Line Number Example 3. Print the total number of lines in a file
  31. If you enjoyed this article, you might also like..

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.


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

02 Cocoa Powder

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.

Читайте также:  Linux check filesystem ntfs

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.

Источник

Unix Sed Tutorial: Append, Insert, Replace, and Count File Lines

This article is part of the on going Unix sed command tutorial series. In our previous articles we learned sed with single commands — printing, deletion, substitute and file write.

Sed provides lot of commands to perform number of operations with the lines in a file.

In this article let us review how to append, insert, replace a line in a file and how to get line numbers of a file.

Let us first create thegeekstuff.txt file that will be used in all the examples mentioned below.

Append Lines Using Sed Command

Sed provides the command “a” which appends a line after every line with the address or pattern.

Sed Append Example 1. Add a line after the 3rd line of the file.

Add the line “Cool gadgets and websites” after the 3rd line. sed “a” command inserts the line after match.

Sed Append Example 2. Append a line after every line matching the pattern

The below sed command will add the line “Linux Scripting” after every line that matches the pattern “Sysadmin”.

Sed Append Example 3. Append a line at the end of the file

The following example, appends the line “Website Design” at the end of the file.

Читайте также:  Запчасти для принтера epson l222

Insert Lines Using Sed Command

Sed command “i” is used to insert a line before every line with the range or pattern.

Sed Insert Example 1. Add a line before the 4th line of the line.

Add a line “Cool gadgets and websites” before 4th line. “a” command inserts the line after match whereas “i” inserts before match.

Sed Insert Example 2. Insert a line before every line with the pattern

The below sed command will add a line “Linux Scripting” before every line that matches with the pattern called ‘Sysadmin”.

Sed Insert Example 3. Insert a line before the last line of the file.

Append a line “Website Design” before the last line of the file.

Replace Lines Using Sed Command

“c” command in sed is used to replace every line matches with the pattern or ranges with the new given line.

Sed Replace Example 1. Replace a first line of the file

The below command replaces the first line of the file with the “The Geek Stuff”.

Sed Replace Example 2. Replace a line which matches the pattern

Replace everyline which has a pattern “Linux Sysadmin” to “Linux Sysadmin – Scripting”.

Sed Replace Example 3. Replace the last line of the file

Sed command given below replaces the last line of the file with “Last Line of the file”.

“=” is a command in sed to print the current line number to the standard output.

The above send command syntax prints line number in the first line and the original line from the file in the next line .

sed ‘=’ command accepts only one address, so if you want to print line number for a range of lines, you must use the curly braces.

Sed Line Number Example 1. Find the line number which contains the pattern

The below sed command prints the line number for which matches with the pattern “Databases”

Sed Line Number Example 2. Printing Range of line numbers

Print the line numbers for the lines matches from the pattern “Oracle” to “Productivity”.

Sed Line Number Example 3. Print the total number of lines in a file

Line number of the last line of the file will be the total lines in a file. Pattern $ specifies the last line of the file.

If you enjoyed this article, you might also like..

  1. 50 Linux Sysadmin Tutorials
  2. 50 Most Frequently Used Linux Commands (With Examples)
  3. Top 25 Best Linux Performance Monitoring and Debugging Tools
  4. Mommy, I found it! – 15 Practical Linux Find Command Examples
  5. Linux 101 Hacks 2nd Edition eBook
  • Awk Introduction – 7 Awk Print Examples
  • Advanced Sed Substitution Examples
  • 8 Essential Vim Editor Navigation Fundamentals
  • 25 Most Frequently Used Linux IPTables Rules Examples
  • Turbocharge PuTTY with 12 Powerful Add-Ons

Comments on this entry are closed.

very nice tutorial !
With Debian version of sed, you need to use the option ‘-i’ to really append lines in your file.By default, the modification appears on the standard output.

Thanks for clarifying how the option -i works on Debian.

How to insert content of file1 on the top of the file2, file3, file4, etc in same directory ?

How I can escape Back slashes in sed. I want to change the pattern or string
from
allow ^127\.0\.0\.1$
to
allow ^192\.168\.1\.10$

Thank You,
Manish

To balast:
for f in `ls file[2-4].txt` ; do
cat file1.txt $f > newfile
cp newfile $f
done

To Manish:
sed ‘s/127\\\.0/192\\\.168/g’ filename
works

cat file2>> file1 should work fine

Very nice tutorial…
But how to write these sed commands in a script… do they work only in command-line?

Thanks! I nominate for the best set of sed instructions on the Internet.

Balaji — they all work in scripts; see here for instance

I want to change the first line of a csv file into lower case. How to do that. thanks

I want to add “something else” after “something” , so i use the below code.
sed ‘
/something/ a\
something else
‘ test.txt
This will just list the contents,but how do i write this new line to the file. I mean the same file and not to a new file.

I agree with arvind, how do you write the changes to the original file. In other words, make the input also the output after sed function has been applied. that was a pun..ha

@Anonymous
cat file1>>file2 only works when the text of file1 may be appended (added to the bottom) to file2.
@Balast
Maybe something like
for f in file[2-4];do sed 1r$f file1>$f;done
could work. It is important not to add quotes around file[2-4], else only the contents of file1 are written to the another files.
for f in file[2-4];do cat file1 $f>$f;done
could also work.
Be careful to first test the strings, because on other computers, it can work different from mine.

Читайте также:  Картридж для принтера hp cz338a

sed -i -e ‘s|foo|bar|’ file.text

Note the “-i” is for in-place. For safety it will make a backup if you supply an extension to -i, as in “-i.bak”.

sed ‘1 c\
> The Geek Stuff’ thegeekstuff.txt

this command doesn’t affect the original file.

I am trying to achieve something similar only solution so far for me is

echo “The Geek Stuff” | sed ‘1a\’ >> thegeekstuff.txt

It should be something cleaner tough.Anyhow hope it helps.

Argh, the formatting in this article is so confusing. There shouldn’t be any linefeed after the backslashes. So it’s not this:

sed ‘ADDRESS i\
Stuff to add’ filename

sed ‘ADDRESS i\Stuff to add’ filename.

Otherwise you get this error:
sed: -e expression #1, char 32: extra characters after command

For those who are on SunOS which is non-GNU, the following code will help to insert a line at top of file, to delete first line or delete last line:

sed ‘1i\^J
line to add’ test.dat > tmp.dat

sed ‘1d’ test.dat > tmp.dat

sed ‘$d’ tmp.dat > test.dat

^J is inserted with ^V+^J
Add the newline after ‘1i.
\ MUST be the last character of the line.
The second part of the command must be in a second line.

i want to channge a file with contents like

want to remove the new line after >. so the result should be
>some text here

how to do it using sed

Is variable substitution supported with the sed insert command ?

I tried to insert the public IP as the first line in /etc/hosts , but its not working
eg:

publicIP=$(curl -s checkip.dyndns.org|egrep -o ‘[0-9\.]+’ 2>/dev/null)
sed “1 i\$ heuristics” /etc/hosts

For inserting lines from the commandline I use the “s” command.
E.g. inserting “the very first line” to the file geek.txt do

sed “1s/^/the very first line\n/”

My problem with the a and i command (working at the commandline) is, that you cannot define the END of the command. So everything following it will be printed – and usually you want to do multiple commands… (though I’m working on a windows-machine, maybe for unix/linux there is a better solution)

How to used the sed append, insert functions in a script to be excuted on remote server. For example I want the command below to be excuted on a remote server using ssh. (solaris)

$ sed ‘$ i\
> Website Design’ thegeekstuff.txt

Very clean and helpful tutorial. Thanks!

Very good tutorial!
But how can i append something at the end of a matched line?
Thanks

When I try the append examples it doesn’t add a newline to the end of the appended line.

If test.txt is:
LINE1
FOO
LINE3

sed ‘/FOO/ a
BAR’ test.txt

LINE1
FOO
BARLINE3

Makes it easy to understand 🙂

@ bob:
sed ‘/FOO/s/$/BAR/’ test.txt
#substitute the end of the line with BAR

Plz explain command
$mv $$ foo.c; head -n 2 foo.c
Where foo.c n $$ r filenames

hi all
i was using this sed command to append a line at the end.
i was using below command dint work
>sed ‘$ a\ my name is kiran’ details.txt
but the changes were not getting saved, when i used below command it was ok
> sed ‘$ i\ my name is kiran’ -i details.txt

HI Please let me know the solution ..if I want to store in a file value such as $$a=20
and 20 is coming from a variable .How can I do that?

thank you! great stuff…

Thanks for the nice tutorial.

But I couldn’t get it to work in shell script and also to get it to update the existing file.

Hey! How to delete or append a line after a pattern match using SED?
I tried using and ,1d – both doesn’t work. Can anyone please help!

hi CJ. To delete lines after a pattern match is:

To append to lines matching the pattern is:

Or if appending after the line matching the pattern is:

hi CJ. Here is the correct way to delete the next file following the line matching the pattern:

Explanation: I created an if-else branching condition labeled as “L0”. If the line does not match the pattern then goto L0 which prints the line. If the line matches the pattern, then print the line first, extract the next line and delete it.

Источник

Поделиться с друзьями
КомпСовет
Adblock
detector