How do i various things using regular expressions?



  • Note: when using sed changes are only displayed to standard out only, but can be in-place. For demo only standard out.

    Working with sample file, named ips & grepfile
    ips:

    10.50.20.3
    10.50.20.4
    10.50.20.5
    10.50.20.6
    10.50.20.7
    10.50.20.8
    10.50.20.9
    10.50.20.10
    

    grepfile

    We're going to need a bigger boat
    Go ahead make my day
    The brothers in arms
    The rain in spain stays mainly on the plain
    aiin
    aain
    

    Change number 50 to 51.

    $ sed 's/50/51/' ips
    10.51.20.3
    10.51.20.4
    10.51.20.5
    10.51.20.6
    10.51.20.7
    10.51.20.8
    10.51.20.9
    10.51.20.10
    

    Change only line 3 from 50 to 51.

    $ sed '3s/50/51/' ips
    10.50.20.3
    10.50.20.4
    10.51.20.5
    10.50.20.6
    10.50.20.7
    10.50.20.8
    10.50.20.9
    10.50.20.10
    

    Delete all blank lines.

    $ sed /^$/d  ips     
    10.50.20.3
    10.50.20.4
    10.50.20.5
    10.50.20.6
    10.50.20.7
    10.50.20.8
    10.50.20.9
    10.50.20.10
    

    Delete blank lines, blank lines containing only tabs and spaces. Between the square brackets, the space and tab characters are generated using the Ctrl-V + Spacebar then Ctrl-V + Tab key.

    $ sed '/^[      ]*$/d' ips
    

    Change every first letter of a work to uppercase.

    $ sed 's/\<./\u&/g' grepfile
    We'Re Going To Need A Bigger Boat
    Go Ahead Make My Day
    The Brothers In Arms
    The Rain In Spain Stays Mainly On The Plain
    Aiin
    Aain
    

    Change the entire file to lowercase.

    $ sed 's/.*/\L&/' grepfile 
    we're going to need a bigger boat
    go ahead make my day
    the brothers in arms
    the rain in spain stays mainly on the plain
    aiin
    aain
    

    Add a word before the IP addresses.

    $ sed  's/[0-9]/Item: &/' ips
    Item: 10.50.20.3
    Item: 10.50.20.4
    Item: 10.50.20.5
    Item: 10.50.20.6
    Item: 10.50.20.7
    Item: 10.50.20.8
    Item: 10.50.20.9
    Item: 10.50.20.10
    

Log in to reply
 

© Lightnetics 2024