Tuesday, June 19, 2012

How to find and replace a string in multiple files

To find and replace a tag across multiple files from command-line in linux, consider this simple shell script:
#!/bin/sh  
today=`date -R`
find . -type f \( -name "*.h" -o -name "*.cpp" \) -print | \
   xargs sed -i 's/{DATE}/'"$today"'"/g'

We scan for regular C++ header and source files. We then pipe the list of files found into 'sed' editor that does line-by-line search and replace.

The only non-trivial part here is the replacement string, '"$today"'. The inside double quotes are needed to let shell expand $today to its value.

No comments:

Post a Comment