7

Imagine the following data stored in file data.txt

1, StringString, AnotherString 545

I want to replace "StringString" with "Strung" with the following code

sed -ir 's/String+/Strung/g' data.txt

But it won't work. This works though:

sed -ri 's/String+/Strung/g' data.txt

I don't see any reason why the order of option flags would matter. Is it a bug or is there an explanation?


Please note that I'm not looking for a workaround but rather why the order of -ir and -ri matters.

Sidenotes: The switch -i "edits the file in place" while -r allows "extended regular expression" (allowing the + operator). I'm running sed 4.2.1 Dec. 2010 on Ubuntu 12.10.

1
  • Sidenote: String+ means Strin(g)+. If you want to match one or more occurrences of "String", use (String)+, but that replaces "AnotherString" with "AnotherStrung", which I don't think is what you want. So, if you want to match exactly two occurrences, use (String){2}, or if you want to match two or more, use (String){2,}.
    – wjandrea
    Aug 29, 2022 at 14:24

2 Answers 2

7

When doing -ir you are specifying that "r" should be the suffix for the backup file.

You should be able to do -i -r if you need them in that order

7

Did you check sed --help or man sed?

-i[SUFFIX], --in-place[=SUFFIX]
     edit files in place (makes backup if extension supplied).
     The default operation mode is to break symbolic and hard links.
     This can be changed with --follow-symlinks and --copy.
1
  • 1
    Doing!! Oh, I just found the file called "data.txtr" in the directory - which was created as a backup. I was expecting a space to seperate the suffix but now it makes sense.
    – somethis
    Jul 8, 2013 at 11:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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