Using sed recursive on a file system

From Andreida
Jump to: navigation, search

Best solution for me so far

use the following phase, do not put it into a script, just replace the 4 variables. When I put it into a script I sometimes get weird behaviour, depending on the search pattern.

sed -i s/$SEARCH/$REPLACE/g  `grep -irl $SEARCH * --include=$PATTERN`

simple change of multiple files, even in multiple directories

If you want to use sed on many files you always should first try to do it the easy way:

sed -i 's/lookingFor/replacingWith/g' */*.c # many files in many directories

But if you have to have more control there are two ways I currently know of:

let find do the searching

find . -type f -exec sed -i 's/lookingFor/replacingWith/g' {} +

find will iterate all directories below the given "." and call the given command for each file. {} will be replaced with the filenames. The + tells find to give many files at the same time to the given command. I do not really understand the use of + here, the manpage does not use it in its examples. But it works. So currently I'd keep it. If I would not use the second solution. Beware of problems with {} when the filenames may contain spaces. Perhaps you'll have to do put something like \' arround them, not sure if there even is a problem. Just a hint.

let grep find the files and then use sed on these files

sed -i 's/lookingFor/replacingWith/g'  `grep -ril 'lookingFor' * --include=*.cpp`

You will have to use ticks around the grep command ! The disadvantage of this is, that you'll have to give the 'lookingFor' twice. But you could use a script too... :-)

# replace-in-files
if [ "$1" = "--help" ] || [ $# -ne 4 ]; then
    echo replace-in-files v 0.1,
    echo this file will replace text in given files
    echo Syntax: $0 \<dir\> \<lookingFor\> \<replaceWith\> \<filePattern\>
    echo Example: $0 . Bug Feature '*.cpp'
    exit 1


sed -i s/$SEARCH/$REPLACE/g  `grep -irl $SEARCH * --include=$PATTERN`