Text Processing: Recursive search and replace
From WikiMLT
Recursive search with Grep
grep -rni 'string or regexp' *
Where:
*– will match to all files and directories (which doesn't start with., alternatively you may need to use./to match everything within the current directory;-r,--recursive– in this case works together with*(or./);-n,--line-number– output the line number where the match is found,-i,--ignore-case– do case insensitive match.
Recursive search and replace with Grep, Xargs and Sed
SEARCHED="string or regexp"
REPLACEMENT="string"
Dry run:
grep -rlZ "$SEARCHED" * | xargs -0 sed 's/${SEARCHED}/${REPLACEMENT}/g'
grep -rlZ "$SEARCHED" * | xargs -0 sed 's/${SEARCHED}/${REPLACEMENT}/g' | grep "$REPLACEMENT"
Replace:
grep -rlZ "$SEARCHED" * | xargs -0 sed 's/${SEARCHED}/${REPLACEMENT}/g' -i.bak
Where:
grep:-Z,--null– a data line ends in 0 byte, not newline (null delimiter);grep:-l,--files-with-matches– print only names of FILEs with selected lines;xargs:-0--null– items are separated by a null, not white-space; disables quote and backslash processing and logical EOF processing;sed:s– substitute/old/new/,g– all matches to the end of the line;-i.bakdo the changes in place and create a backup file.
Simple example:
grep -rliZ 'hw\.2022' | xargs -0 sed 's#hw\.2022#homework/hw.2022#g' -i.bak