sedspacessubstitution

Matching strings even if they start with white spaces in SED


I'm having issues matching strings even if they start with any number of white spaces. It's been very little time since I started using regular expressions, so I need some help

Here is an example. I have a file (file.txt) that contains two lines

#String1='Test One'
String1='Test Two'

Im trying to change the value for the second line, without affecting line 1 so I used this

sed -i "s|String1=.*$|String1='Test Three'|g"

This changes the values for both lines. How can I make sed change only the value of the second string?

Thank you


Solution

  • With gnu sed, you match spaces using \s, while other sed implementations usually work with the [[:space:]] character class. So, pick one of these:

    sed 's/^\s*AWord/AnotherWord/'
    sed 's/^[[:space:]]*AWord/AnotherWord/'
    

    Since you're using -i, I assume GNU sed. Either way, you probably shouldn't retype your word, as that introduces the chance of a typo. I'd go with:

    sed -i "s/^\(\s*String1=\).*/\1'New Value'/" file
    

    Move the \s* outside of the parens if you don't want to preserve the leading whitespace.