Issue
I'm running MacOS Ventura 13.4, and I want to use sed to insert the following meta
tags (in the given order) to an HTML file index.html
that is located under the directory called public
.
<meta http-equiv='cache-control' content='no-cache'>
<meta http-equiv='expires' content='0'>
<meta http-equiv='pragma' content='no-cache'>
I have the following script:
#!/bin/bash
sed -e '/\<head\>/a<meta http-equiv="pragma" content="no-cache">' \
-e '/\<head\>/a<meta http-equiv="expires" content="0">' \
-e '/\<head\>/a<meta http-equiv="cache-control" content="no-cache">' > public/index.html
However, this throws the following error:
sed: 1: "/<head>/a<meta http-e ...": command a expects \ followed by text
Any ideas how to fix this?
Solution
Like the error message says, MacOS sed
wants the text to insert to have a backslash.
I'm also guessing you mean <head>
, not just any head
with a word boundary on either side (and if that's what you need, the syntax on MacOS for that (and generally on POSIX) is [[:<:]]
and [[:>:]]
(sic)).
sed -e '/<head>/a\
<meta http-equiv="cache-control" content="no-cache">\
<meta http-equiv="expires" content="0">\
<meta http-equiv="pragma" content="no-cache">'
You can't nest single quotes, so I switched to double quotes around the attributes. If you genuinely require single quotes, try '"'"'
(which is ending single quote for the string beginning after sed -e
, beginning double quote, lone literal single quote, ending double quote, beginning single quote to continue the long string).
You are not revealing where the standard input is supposed to come from; did you mean to run this with sed -i ''
perhaps? Though then you can't use redirection before the file name.
sed -i '' -e '/<head>/a\
<meta http-equiv="cache-control" content="no-cache">\
<meta http-equiv="expires" content="0">\
<meta http-equiv="pragma" content="no-cache">' public/index.html
(Notice that this will permanently alter the original file. Don't use -i
if that's not what you want.)
Technically, there is no requirement for the closing wedge after <head
to be immediately adjacent to the header name, or even on the same line. If you need complete robustness, sed
is simply the wrong tool for this (or, well, it's Turing complete, so you could implement a proper XML parser if you really wanted to; but really, you don't). On MacOS, maybe look at the xmllint
tool which is included out of the box (at least with XCode) or a proper XML tool like xmlstarlet
.
Answered By - tripleee Answer Checked By - Clifford M. (WPSolving Volunteer)