Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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
up vote 1 down vote accepted
head -n1 file | grep -q "^<?php" || sed -i "1s/^/<?php /" file
share|improve this answer

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

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

You must log in to answer this question.