Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

The question is related to the question "Unix: Add a Tag to the beginning of each file?".

How can I put the tag only to the files that do not contain the tag, such as <?php, already?

share|improve this question
add comment

3 Answers 3

up vote 1 down vote accepted
head -n1 file | grep -q "^<?php" || sed -i "1s/^/<?php /" file
share|improve this answer
add comment

Suitably modified version of my answer to the original question:

perl -0777 -p -i -e 's/^/<?php/g unless m/^<\?php/' testfile

Running this command with -i.bak instead of -i will preserve a backup of the original files with a .bak extension.

Edit: Updated the match from m/<?php/ to m/^<\?php/ to make it match only the beginning of the file, and to escape the ? character.

share|improve this answer
add comment

You want || (OR). If the left hand is true, it will not bother with the right hand. e.g.

test "$(grep PATTERN FILE)" || sed COMMAND FILE
share|improve this answer
    
The test $( ) part here is not needed, and even breaks the whole test. grep -q blah || is enough. –  grawity Sep 6 '09 at 20:33
add comment

Your Answer

 
discard

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