Searching and Replacing with grep and sed

Unix commands grep and sed can be used to efficiently search and replace strings in a file, a directory, or files acrose multiple directories. Specifically, grep is used to search for a certain string, and sed is used to replace the strings.

Search using grep

grep -l somematchstring somefile.txt

This command searches somematchstring in the file somefile.txt. The option -l means it will print names of files containing matches.

grep -rl somematchstring somedir/

This command searches somematchstring in all files under the directory somedir. The option -l again means it will print names of files containing matches. The option -r means it will go recursively into all subdirectories.

grep -l somematchstring somedir/*.java

This searches somematchstring in all .java files under the directory somedir.

Search and Replace using sed

grep -rl somematchstring somedir/ | xargs sed -i 's/somematchstring/somereplacestring/g'

The grep command will list all files under the directory somedir/ containing somematchstring. The file names are passed on through the pipe ‘|’ delimiter. Then the sed command will replace somematchstring by somereplacestring.

Note that the grep command will pipe only files matching somematchstring to sed. The pipe ‘|’ delimiter is efficient when searching through a lot of files.

The following is another example.

grep -rl 'Windows' ./ | xargs sed -i 's/Windows/Linux/g'

This will search for ‘Windows’ in all files under the current directory, and replace ‘Windows’ by ‘Linux’ for each occurrence ‘Windows’ in each file.

Comments

comments