I have many .html files and I need to add a meta tag after <head>'s start tag in each file.

How I can do that?

Is vimsuited for the task?


In vim, you can do:

:%s/<head\b[^>]*>/& <meta foo="bar">/g

You could also do this in GNU sed, which would possibly be more fitting:

for file in *.html; do
    sed -i 's/<head\b[^>]*>/& <meta foo="bar">/g' "$file"

Be warned, -i breaks symlinks.

  • for file in *.html; do sed -i 's/<head[^>*>/& <link rel="shortcut icon" href="../favicon.ico" type="image/x-icon"/>/g'; done – Chalist Dec 25 '12 at 13:32
  • this error: sed: -e expression #1, char 90: unterminated `s' command – Chalist Dec 25 '12 at 13:33
  • sed -i.bkp it will edit original files, and also take backup as filename.bkp – Rahul Patil Dec 25 '12 at 13:43
  • If that HTML is HTML5, your regular expression will erroneously match header tags too. Make it match only if “head” ends at word boundary. – manatwork Dec 25 '12 at 13:50
  • @manatwork Good catch! Will fix it now. – Chris Down Dec 25 '12 at 14:03
sed -i '/PATTERN/ a\
    Line which you want to append' filename

for this example

sed -i '/<HEAD>/a <meta>' test.txt

Result :


The above command will append new line after the string get matched. However this will give wrong result if file has input string as



</HEAD>  //which is wrong.

May be we can try this approach:

sed -i 's/<HEAD>/<HEAD><meta>/' filename
  • <head><foo> is legal in HTML, so this will not work as expected if such a condition exists. For example, this would result in <head><foo>\n<meta ...> in such a case. – Chris Down Dec 25 '12 at 13:35
  • Sorry chris..i didn't noticed that bug..thanks – fewtalks Dec 25 '12 at 14:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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