acub
acub

Reputation: 3

Match word ignoring same word with extra character in sed

The following works in Javascript as a match:

[^\$]fileref.*

However, in sed the regex does not match anything. I would like to replace a variable reference in a bash file while ignoring the variable identifier. The premise is that I have a default placeholder file that needs to be updated from a shell script with sed -i. I can't locate a reason as to why sed is having an issue with this expression.

Sed test example:

echo -e 'fileref=old\n./executable $fileref' | sed 's/[^\$]fileref.*/fileref=replaced/g'

Output from gnu sed (ubuntu or centOS) where no match is found:

fileref=old
./executable $fileref

Desired output:

fileref=replaced
./executable $fileref

Upvotes: 0

Views: 130

Answers (2)

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89557

"No $ before fileref" can be expressed like this: "a character that isn't a $ or no character at all before fileref"

echo -e 'fileref=old\n./executable $fileref' | sed 's/\([^$]\|^\)fileref.*/\1fileref=replaced/g'

The same with Javascript:

var result = str.replace(/([^$]|^)fileref.*/, '$1fileref=replaced');

Upvotes: 2

Anthony Staunton
Anthony Staunton

Reputation: 115

echo -e 'fileref=old\n./executable $fileref' | sed 's/^fileref.*$/fileref=replaced/g'

gives the following

fileref=replaced
./executable $fileref

by putting in [^\$] you are saying to search for $ at the start of a line

Upvotes: 0

Related Questions