Question

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

Was it helpful?

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.

OTHER TIPS

There are a couple of solutions you could use to go about your problem

If you want to ignore lines that begin with a comment character such as '#' you could use something like this:

sed -i "/^\s*#/! s|String1=.*$|String1='Test Three'|g" file.txt

which will only operate on lines that do not match the regular expression /.../! that begins ^ with optional whiltespace\s* followed by an octothorp #

The other option is to include the characters before 'String' as part of the substitution. Doing it this way means you'll need to capture \(...\) the group to include it in the output with \1

sed -i "s|^\(\s*\)String1=.*$|\1String1='Test Four'|g" file.txt

With GNU sed, try:

sed -i "s|^\s*String1=.*$|String1='Test Three'|" file

or

sed -i "/^\s*String1=/s/=.*/='Test Three'/" file

Using awk you could do:

awk '/String1/ && f++ {$2="Test Three"}1' FS=\' OFS=\' file
#String1='Test One'
String1='Test Three'

It will ignore first hits of string1 since f is not true.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top