I'm trying to use sed to replace every instance of old in the file with new. Now it works with lowercase strings, but I need it to replace certain strings that are capitalized. For Example replace OLD with NEW. I know sed can do this, but I can't get it quite right?

for file in .; do
  cat $file
  sed 's/old/new/g' $file | tee $file
  • if you want to replace "OLD", why are you searching for "old"?
    – Jeff Schaller
    Oct 22, 2018 at 14:07

4 Answers 4


Do you know about the i / I flag to the s command (GNU extension, though)?

  • I have some idea about it, if I'm correct it you put i / I after the s? I have very little experience sed, if I'm wrong tell me.
    – Josh Adams
    Oct 22, 2018 at 13:51
  • No, adjacent to the g.
    – RudiC
    Oct 22, 2018 at 13:58
  • adding /I would make the search case-insensitive, but wouldn't the replacement remain "new" versus the desired "NEW"?
    – Jeff Schaller
    Oct 22, 2018 at 14:07
  • Oh Ok, that explains why I couldn't get it too work, now it's working thank you.
    – Josh Adams
    Oct 22, 2018 at 14:07

To replace "old" with "new" and "OLD" with "NEW", just tell sed to do both:

for file in ./*; do
  cat "$file"
  sed -i -e 's/old/new/g; s/OLD/NEW/g' "$file"

Don't forget to quote the variables, in case you have a file named some filename (with spaces, newlines, or tabs in them). I also added -i, a GNU sed extension, given that you indicated that you could use the GNU /i flag extension, to tell sed to edit the file in-place instead of relying on tee and buffers to do it.


You can use perl:

$ cat file
old news
OLD news
old Old oLD news
older news
$ perl -pe 's{(old)}{ ($tmp = $1) =~ tr/OLDold/NEWnew/; $tmp }ieg' file
new news
NEW news
new New nEW news
newer news

That uses the s/// operator to do search and replace, and in the replacement, it transliterates the characters from "old" to "new", preserving the individual characters' case. This only works because "old" and "new" are the same string length.

I need to use a temp variable because $1 is a read-only value.


Given that the strings are of the same size, all this commands will work:

<infile sed    'y/OLDold/NEWnew/' >outfile
<infile tr     'OLDold'  'NEWnew' >outfile
        sed -i 'y/OLDold/NEWnew/' infile

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .