≡ Menu

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

Linux Sed Examples - File Manipulation CommandsThis 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.

$cat thegeekstuff.txt
Linux Sysadmin
Databases - Oracle, mySQL etc.
Security (Firewall, Network, Online Security etc)
Storage in Linux
Productivity (Too many technologies to explore, not much time available)
Windows- Sysadmin, reboot etc.

Append Lines Using Sed Command

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

Syntax:

#sed 'ADDRESS a\
	Line which you want to append' filename

#sed '/PATTERN/ a\
	Line which you want to append' filename

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 '3 a\
> Cool gadgets and websites' thegeekstuff.txt

Linux Sysadmin
Databases - Oracle, mySQL etc.
Security (Firewall, Network, Online Security etc)
Cool gadgets and websites
Storage in Linux
Productivity (Too many technologies to explore, not much time available)
Windows- Sysadmin, reboot etc.

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 '/Sysadmin/a \
> Linux Scripting' thegeekstuff.txt

Linux Sysadmin
Linux Scripting
Databases - Oracle, mySQL etc.
Security (Firewall, Network, Online Security etc)
Storage in Linux
Productivity (Too many technologies to explore, not much time available)
Windows- Sysadmin, reboot etc.
Linux Scripting

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.

$ sed '$ a\
> Website Design' thegeekstuff.txt

Linux Sysadmin
Databases - Oracle, mySQL etc.
Security (Firewall, Network, Online Security etc)
Storage in Linux
Productivity (Too many technologies to explore, not much time available)
Windows- Sysadmin, reboot etc.
Website Design

Insert Lines Using Sed Command

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

Syntax:

#sed 'ADDRESS i\
	Line which you want to insert' filename

#sed '/PATTERN/ i\
	Line which you want to insert' filename

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 '4 i\
> Cool gadgets and websites' thegeekstuff.txt

Linux Sysadmin
Databases - Oracle, mySQL etc.
Security (Firewall, Network, Online Security etc)
Cool gadgets and websites
Storage in Linux
Productivity (Too many technologies to explore, not much time available)
Windows- Sysadmin, reboot etc.

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 '/Sysadmin/i \
> Linux Scripting' thegeekstuff.txt

Linux Scripting
Linux Sysadmin
Databases - Oracle, mySQL etc.
Security (Firewall, Network, Online Security etc)
Storage in Linux
Productivity (Too many technologies to explore, not much time available)
Linux Scripting
Windows- Sysadmin, reboot etc.

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.

$ sed '$ i\
> Website Design' thegeekstuff.txt

Linux Sysadmin
Databases - Oracle, mySQL etc.
Security (Firewall, Network, Online Security etc)
Storage in Linux
Productivity (Too many technologies to explore, not much time available)
Website Design
Windows- Sysadmin, reboot etc.

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.

Syntax:

#sed 'ADDRESS c\
	new line' filename

#sed '/PATTERN/ c\
	new line' filename

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 '1 c\
> The Geek Stuff' thegeekstuff.txt

The Geek Stuff
Databases - Oracle, mySQL etc.
Security (Firewall, Network, Online Security etc)
Storage in Linux
Productivity (Too many technologies to explore, not much time available)
Windows- Sysadmin, reboot etc.

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

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

$ sed '/Linux Sysadmin/c \
> Linux Sysadmin - Scripting' thegeekstuff.txt

Linux Sysadmin - Scripting
Databases - Oracle, mySQL etc.
Security (Firewall, Network, Online Security etc)
Storage in Linux
Productivity (Too many technologies to explore, not much time available)
Windows- Sysadmin, reboot etc.

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

$ sed '$ c\
> Last line of the file' thegeekstuff.txt

Linux Sysadmin
Databases - Oracle, mySQL etc.
Security (Firewall, Network, Online Security etc)
Storage in Linux
Productivity (Too many technologies to explore, not much time available)
Last line of the file

Print Line Numbers Using Sed Command

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

Syntax:

#sed '=' filename

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.

Syntax:

# sed -n '/PATTERN/,/PATTERN/ {
=
p
}' filename

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 -n '/Databases/=' thegeekstuff.txt

2

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 -n '/Oracle/,/Productivity/{
> =
> p
> }' thegeekstuff.txt

2
Databases - Oracle, mySQL etc.
3
Security (Firewall, Network, Online Security etc)
4
Storage in Linux
5
Productivity (Too many technologies to explore, not much time available)

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.

$ sed -n '$=' thegeekstuff.txt

6
Add your comment

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 Linux 101 Hacks Book

Bash 101 Hacks Book Sed and Awk 101 Hacks Book Nagios Core 3 Book Vim 101 Hacks Book

Comments on this entry are closed.

  • linuxindetails November 12, 2009, 3:31 am

    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.

  • Ramesh Natarajan December 10, 2009, 6:02 pm

    @linuxindetails,

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

  • Balast July 3, 2010, 12:29 pm

    Hi,

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

  • Manish November 4, 2010, 8:53 am

    Hi

    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

  • frankhuang November 17, 2010, 2:25 am

    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

  • Anonymous December 1, 2010, 3:19 am

    @ Blast

    cat file2>> file1 should work fine

  • Balaji May 6, 2011, 3:25 am

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

  • David Liontooth June 18, 2011, 9:26 am

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

  • David Liontooth June 18, 2011, 9:28 am

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

  • mary July 29, 2011, 3:14 pm

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

  • arvind January 12, 2012, 7:49 am

    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.

  • macmadness86 April 11, 2012, 9:33 am

    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

  • phamming May 11, 2012, 5:37 am

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

  • Steve August 27, 2012, 8:20 pm

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

  • shridhara November 2, 2012, 4:11 am

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

    this command doesn’t affect the original file.

    help me

  • Carlos Luna November 3, 2012, 12:33 pm

    Hi Shridhara,

    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.

    Carlos

  • Steve Bennett February 5, 2013, 6:17 pm

    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

    It’s this:

    sed ‘ADDRESS i\Stuff to add’ filename.

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

  • madxkatz February 19, 2013, 1:56 am

    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.

  • Nidhi March 29, 2013, 12:09 am

    i want to channge a file with contents like

    }
    some text here

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

    how to do it using sed

  • Reynold May 18, 2013, 12:44 pm

    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\${publicIP} heuristics” /etc/hosts

    Any idea ?

  • Holger June 28, 2013, 3:30 am

    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)

  • sanjay August 29, 2013, 5:37 am

    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

  • Pat October 23, 2013, 3:51 am

    Very clean and helpful tutorial. Thanks!

  • igor November 26, 2013, 1:37 pm

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

  • Bob Donahue December 12, 2013, 8:40 am

    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

    gives

    LINE1
    FOO
    BARLINE3

  • Anonymous December 20, 2013, 10:04 am

    Makes it easy to understand 🙂

  • igor December 20, 2013, 2:26 pm

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

  • Preeti April 27, 2014, 6:32 am

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

  • kiran July 15, 2014, 8:41 pm

    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

  • nagaraju December 18, 2014, 1:16 am

    amazing……..

  • Sagar June 8, 2015, 6:29 am

    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?

  • zwang March 2, 2016, 6:25 pm

    thank you! great stuff…

  • Prabhakaran March 20, 2016, 11:04 pm

    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.

  • CJ May 17, 2016, 4:27 pm

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

  • syscools March 5, 2017, 1:23 am

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

    sed '/search string/d' file.txt
    

    To append to lines matching the pattern is:

    sed '/search string/s/$/ <------------/' file.txt
    

    Or if appending after the line matching the pattern is:

    sed '/search string/a\this is a test' file.txt
    
  • syscools March 5, 2017, 1:37 am

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

    sed -n '/search string/!bL0;p;N;d;:L0;p' file.txt
    

    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.