Using sed to find and replace a range of numbers

12,645

Solution 1

Use [0-9] instead of ? to match a single digit.

sed 's/30[0-9][0-9]\" authentication=\"someuniqueauthkey/'$1'\" authentication=\"someuniqueauthkey/' $configFile

Solution 2

To match a number you can use [0-9]\{2} or \d\{2}

In your case ?? would also match 30 only.

You can find a nice overview of regular expressions here.

Solution 3

First, the matching expression must be 30.. not 30??
Then, you seem to have forgotten the -e argument to sed.
Try with:

sed -e 's/30..\" authentication=\"someuniqueauthkey/'$1'\" authentication=\"someuniqueauthkey/' $configFile

Solution 4

This might work for you:

sed 's/30[0-9][0-9]\(" authentication="someuniqueauthkey\)/'$1'\1/' $configFile
Share:
12,645
Jarob22
Author by

Jarob22

Updated on June 04, 2022

Comments

  • Jarob22
    Jarob22 almost 2 years

    first poster here.

    Trying to use sed to find and replace a word. Code is as follows:

    configFile=ConnectionConfig.xml
    sed 's/30??\" authentication=\"someuniqueauthkey/'$1'\" authentication=\"someuniqueauthkey/' $configFile
    

    And I'd run the file like this:

    ./choosePort.sh 3001
    

    When I run this code, there are no errors given like bad regex format, it just doesn't replace anything and the contents of tempXml.xml are just the contents of ConnectionConfig, unchanged.

    What I'd like to be able to do is recognise any number 3000 - 3099 in the 30?? part of the expression, which I thought was what the '?' did.

    The input line I'm trying to change is:

    <host id="0" address="someip" port="3001" authentication="someauthkey"
    

    Thanks in advance. (Ip and authkeys in file blanked out for security reasons).