Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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?

Can vim help me?

share|improve this question
add comment

2 Answers 2

up vote 4 down vote accepted

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"
done

Be warned, -i breaks symlinks.

share|improve this answer
    
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
    
thanks a lot. it's done :D. I love linux :) –  chalist Dec 25 '12 at 13:41
    
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
show 1 more comment
sed -i '/PATTERN/ a\
    Line which you want to append' filename

for this example

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

Result :

<HEAD>
<meta>
</HEAD>

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><TITLE></TITLE>
</HEAD>

Result:

<HEAD><TITLE></TITLE>
<meta>
</HEAD>  //which is wrong.

May be we can try this approach:

sed -i 's/<HEAD>/<HEAD><meta>/' filename
share|improve this answer
    
<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
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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