8

I'm fairly new to working with bash / shell scripts so please excuse me if this is really simple. I am trying to replace inline a file that is nested in a directory, however I receive

Invalid command code .

when I try

sed -i 's/\([^.]*\).css/\1.min.css/g' ./bobby/templates/layout.html;

I have a big hunch it's ./bobby/templates/layout.html that's throwing the error, but I'm unsure how to reformat this to be a valid filepath.

AdminBee
  • 22,803

1 Answers1

15

It looks like your version of sed requires a suffix argument for the -i option. That means it's probably on a Mac or FreeBSD machine.

sed is then interpreting your sed script as the suffix, and the filename as the sed script....hence the error message Invalid command code ., because that's the first character of the filename.

Try:

sed -i .bak 's/\([^.]*\)\.css/\1.min.css/g' ./bobby/templates/layout.html

I've added a backslash to escape the . in the LHS of the s/// command (otherwise it will match any character, not just a literal .), and got rid of the ; at the end of the filename - that would only be needed if there was more than one command in the same line.

The sed script will do an in-place edit of the file, and make a backup as .../layout.html.bak

Alternatively, you can do it with perl. e.g.

perl -i -p -e 's/([^.]*)\.css/$1.min.css/g' ./bobby/templates/layout.html

BTW, the regular expressions used in both the sed and perl versions may change more than you expect, because it's unlikely that there will be just filename.css on a line by itself in a .html file. I'd test it first without the -i option.

You may want something more like s:(/[^.]*)\.css:$1.min.css:g, so that it only changes a filename if it's immediately preceded by a slash character. It's impossible to be more specific than that without seeing what your actual input file looks like.

cas
  • 78,579
  • 3
    I appreciate the thorough answer. And yes I am using a Mac. – irahorecka Aug 05 '21 at 16:36
  • For correct answer https://stackoverflow.com/a/42667816/1368703 – Wyrmwood Jul 06 '23 at 20:29
  • @Wyrmwood how, exactly, is that any more "correct" than what I wrote? It's the same answer ("sed on mac requires an arg for the -i option") in slightly different words. – cas Jul 06 '23 at 23:38
  • On MACOS adding '' after the -i worked for me. Not sure why. Seemingly the MAC version of sed is the BSD version. still means nothing to me, but it worked. :) – TheArchitecta Oct 18 '23 at 12:12
  • @cas, I did not understand your answer the linked answer helped and then I understood your answer a little more. I assume all that is required to be said is that -i requires a zero length argument??? I up voted your answer as ultimately it helped and had content. – TheArchitecta Oct 18 '23 at 12:15