0

I have a simple text file:

>cat a
A=B

Using sed, I am trying to change this to:

setenv A B

My sed command which doesn't work is :

>sed -ir 's/([^\=]+)\=(.*)/setenv \1 \2/' a
sed: -e expression #1, char 30: invalid reference \2 on `s' command's RHS

However the same command words when I remove the -i option:

>sed -r 's/([^\=]+)\=(.*)/setenv \1 \2/' a
setenv A B

I don't have this problem when I use basic regular expression:

>sed -ir 's/\([^=]*\)=\(.*\)/setenv \1 \2/' a
>cat a
setenv A B

My sed version is :

>sed --version
sed (GNU sed) 4.2.2

Any suggestions on what could be wrong?

3

The -i option of GNU Sed is somewhat non-conformant in that it can optionally take an argument specifying a backup suffix

   -i[SUFFIX], --in-place[=SUFFIX]

          edit files in place (makes backup if SUFFIX supplied)

So sed -ir 's/pattern/replacement' a means "edit file a in place, making a backup file ar" rather than "edit file a in place, using extended regular expression syntax"

You want either

sed -i -r 's/pattern/replacement' a

or (less clear IMHO)

sed -ri 's/pattern/replacement' a
  • -r is also not portable. Try with -E which seems to be more widely supported; or use traditional regex in pattern. (If it doesn't contain any regex metacharacters, the -E or -r doesn't do anything useful anyway.) – tripleee Jul 31 '18 at 11:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.