Search and replace multiple files including subdirectories

I want to search for all occurrences of:


In the current directory and its subdirectories and replace each occurrence with:

<input type="hidden" name="_token" value="<cfoutput>#STOKEN#</cfoutput>"/>

I tried the following on one file. The file was touched — last modified date was changed — but the replacement was not made:

sed -i -re 's/</form>/<input type="hidden" name="_token" value="<cfoutput>#STOKEN#</cfoutput>"></form>/gi' ./math.cfm

What am I missing? Is there a better command to use for this?

Asked By: PeterKA


The < and > elements have special meaning in sed regex (as word boundaries).

Don’t make things hard by using / as sed’s separator and trying to get the escaping right – choose an alternate delimiter that doesn’t appear in your text, such as % or |.

The i (insert) command seems to me to be a more natural choice than the s command for this task: you could try

'%</form>% i<input type="hidden" name="_token" value="<cfoutput>#STOKEN#</cfoutput>"/>'

To apply such a command to subdirectories recursively, you can supply the sed command as a -exec or -execdir argument to find e.g.

find path/to/dir -type f -name '*.cfm' -execdir sed -i -re '%</form>% i<input type="hidden" name="_token" value="<cfoutput>#STOKEN#</cfoutput>"/>' {} +

Alternatively, you could use the shell’s globstar functionality.

Answered By: steeldriver
Categories: Answers Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.