-1

I have a (Nginx) config file like

types {
    text/html      html htm shtml;
    text/css       css;
    text/xml       xml;
}

In which I'd like to append an entry (wherever in the file) such as for example

types {
    text/html      html htm shtml;
    text/css       css;
    text/xml       xml;
    image/gif      gif;
}

I tried using sed as in this post

sed -i "\$i hello" mimes.types
sed: 1: "mimes.types": invalid command code m

I'm testing on MacOS with fish, but got the same error on bash.

Which command could I use here? Many thanks!

Inian
  • 71,145
  • 9
  • 121
  • 139
Mornor
  • 2,938
  • 7
  • 28
  • 61

2 Answers2

1

This will do an in-place edit, inserting a line with hello immediately before any line that consists of a } and optional whitespace:

perl -p -i -l -e 'print "hello" if /^\s*}\s*$/' mimes.types

Limitation with the above: if there are multiple } lines then you will get multiple hello lines.

The following will only print hello the once, even if there are multiple } lines:

perl -p -i -l -e 'print("hello"), $done=1 if /^\s*}\s*$/ && !$done' mimes.types 

Explanation:

  • -p loop over input, print every input line after executing the perl code
  • -i edit the file in place (remove this to write to standard output instead)
  • -l strips newline characters from input and appends them to output
  • -e 'print "hello" if /^\s*}\s*$/' executes the print if the default variable ($_), which contains the line that was read in, matches the regular expression

In the second example, the variable $done is not explicitly initialised, but the !$done test works with an undef value the same as it would with an explicit 0.

alani
  • 11,960
  • 2
  • 10
  • 22
0

I think the error stems from a small difference between GNU sed (used on most Linux systems) and BSD sed (used on MacOS). The latter expects a mandatory argument to -i. Try the following

sed -i .bak "\$i hello" mimes.types
Socowi
  • 22,529
  • 3
  • 25
  • 46