3

I am trying to replace (for instance) 6.0 by 6.1 in a file, without 640 being replaced by 6.1

I have currently:

sed -i "s/$previousName/$newName/" 'myFile'

I think that the solution could be in here, but I don't find the right solution.

EDIT both string are inside a variable and the question this is supposed to be a duplicate of doesn't treat this case

Sharcoux
  • 5,546
  • 7
  • 45
  • 78
  • Ok, I read your link and I found `sed -e 's/[]\/$*.^|[]/\\&/g'` What is this, what does it do and where am I supposed to set my variable in this? – Sharcoux Sep 23 '16 at 11:58

3 Answers3

8

Using an inner sed:

sed -i "s@$(echo $previousName | sed 's/\./\\./g')@$newName@g" myFile
Ori Popowski
  • 10,432
  • 15
  • 57
  • 79
3

Try this:

sed -i "s/6\.0/6.1/" 'myFile'

The key is to escape the . character in the pattern which has special meaning. By default it matches any character (including 0 in 640), whereas with a \ in front of it, it only matches a literal ..

Since you have the pattern in a variable, you could escape the . in it first like this:

previousNameE="$(sed -e 's/\./\\./' <<< "$previousName")"
sed -i "s/$previousNameE/$newName/" 'myFile'
redneb
  • 21,794
  • 6
  • 42
  • 54
1

if perl is acceptable:

perl -i -pe "s/\Q$previousName/$newName/" 'myFile'

From perldoc for \Q

Returns the value of EXPR with all the ASCII non-"word" characters backslashed. (That is, all ASCII characters not matching /[A-Za-z_0-9]/ will be preceded by a backslash in the returned string, regardless of any locale settings.) This is the internal function implementing the \Q escape in double-quoted strings

Another example:

$ echo '*.^[}' | perl -pe 's/\Q*.^[}/q($abc$)/e'
$abc$

Further reading: Perl flags -pe, -pi, -p, -w, -d, -i, -t?

Community
  • 1
  • 1
Sundeep
  • 23,246
  • 2
  • 28
  • 103
  • Cool ! What is the Q for ? I could search myself, but I think of potential futur readers – Sharcoux Sep 23 '16 at 11:52
  • Can't open perl script "s/\Q1.6.0/1.6.1/": no folder or file of this type – Sharcoux Sep 23 '16 at 12:00
  • what does `type perl` return? does this print hello? `perl -e 'print "Hello\n"'` – Sundeep Sep 23 '16 at 12:01
  • perl is hashed (/usr/bin/perl), and yes, I get Hello – Sharcoux Sep 23 '16 at 12:03
  • @Sharcoux, oops my mistake, missed `-pe` in solution.. can you try now? – Sundeep Sep 23 '16 at 12:05
  • 1
    I think it's ok now, thanks. I'll keep this solution in mind. Seems easier than sed. Would you mind adding a link to [this](http://stackoverflow.com/questions/6302025/perl-flags-pe-pi-p-w-d-i-t) in your answer, or an explaination of i and pe? – Sharcoux Sep 23 '16 at 12:12
  • 1
    thanks, easier to link than adding my own explanation.. `perl -i -pe` is equivalent to `sed -i` to put it in simple terms – Sundeep Sep 23 '16 at 12:18