Wednesday, August 8, 2012

sed replace example

The following command is probably one of the most useful commands one can use to edit parts of files.

grep -lr "int main()" * | xargs sed -i -e 's/foo/bar/'

This will replace all occurrences of foo with bar in all files recursively if they contain int main(). E.g.

int main() {
    int foo = 0;

    return foo;
}

Will be changed to:

int main() {
    int bar = 0;

    return bar;
}