• VMware

    Learn about VMware virtualization for its products like vsphere ESX and ESXi, vCenter Server, VMware View, VMware P2V and many more

  • Linux

    Step by step configuration tutorials for many of the Linux services like DNS, DHCP, FTP, Samba4 etc including many tips and tricks in Red Hat Linux.

  • Database

    Learn installation and configuration of databases like Oracle, My SQL, Postgresql, etc including many other related tutorials in Linux.

  • sed: Replace string based on line number (certain line)

    Here our requirement is that we have a file where we have to perform a string replacement but based on line number.

    Below is our sample data /tmp/file
    1 This is line one
    2 This is line two
    3 This is line three
    4 This is line four
    5 This is line one
    6 This is line two
    7 This is line three
    8 This is line four




    Example 1
    Replace "one" with "your text" at line number 5, note that the replacement must only happen at line number 5 as we also have 'one' at line number 1

    Solution
    # sed '5s/one/your text/g' /tmp/file

    1 This is line one
    2 This is line two
    3 This is line three
    4 This is line four
    5 This is line your text
    6 This is line two
    7 This is line three
    8 This is line four

    To perform in line replacement in the same file
    # sed -i '5s/one/your text/g' /tmp/file





    Example 2
    Replace "four" with "your text" at line number 8, note that the replacement must only happen at line number 5 as we also have 'four' at line number 4

    Solution
    # sed '8s/four/your text/g' /tmp/file

    1 This is line one
    2 This is line two
    3 This is line three
    4 This is line four
    5 This is line one
    6 This is line two
    7 This is line three
    8 This is line your text

    To perform in line replacement in the same file
    # sed -i '8s/four/your text/g' /tmp/file
    IMPORTANT NOTE :  Do not use this unless you are very sure the command will not impact anything else, it is always recommended to take a backup of such file where you plan to do in place replacement

    Deepak Prasad

    is a techie and an author who is still trying to survive in this IT generation with very little knowledge he has on Linux/Unix, VMware, SAN Storage, Automation, networking etc

    You can follow him on Facebook or Google+


    Do you also have something to share here?
    Join GoLinuxHub Team as an Author, Click here for more information
    sed: Replace string based on line number (certain line) sed: Replace string based on line number (certain line) Reviewed by Deepak Prasad on Sunday, June 25, 2017 Rating: 5

    No comments:

    Powered by Blogger.