<-- home

Search and Replace on console

My intent with this post is to enumerate the ways I know of searching and replacing in unix consoles. In the end I’ll elect the best one.


Grep grep -R "foo" ~/bar


ack -R "foo" ~/bar

Search and Replace

Awk awk '{gsub(/pattern/,"replacement")}' file

Perl perl -pi -w -e 's/SEARCH_FOR/REPLACE_WITH/g;' *.txt

Search with backup

perl -e "s/old_string/new_string/g;" -pi.save $(find DirectoryName -type f)


tr 'string to be converted' 'string to replace' <file.txt |tee file.txt

Find e Sed

find module/ -name "*.php" -exec sed -i "s/Importando/Importing/g" {} \;

Find, Sed e Xargs

find . -name "*.php" -print | xargs sed -i 's/foo/bar/g'

Grep e Xargs

Este método eu utilizo para buscar e fazer algo diferente de substituir.

ls -a | egrep -l '^\..{2,}' | xargs rm -rf {} \;

O l como parametro para o egrep serve para que o comando mostre somente os nomes dos arquivos, ideal para utilizar com comandos.

The best one

Searching ack -Rl "pattern to search"

Replacing ``` s1=”patterToSearch” ack -Rl $s1 | xargs sed -i

”s/$s1/patternToReplace/g” ```


1. http://lifehacker.com/5810026/quickly-find-and-replace-text-across-multi ple-documents-via-the-command-line 2. http://askubuntu.com/questions/20414/find-and-replace-text-within-a-file -using-commands 3. http://www.brunolinux.com/02-The_Terminal/Find_and%20Replace_with_Sed.ht ml 4. https://rushi.wordpress.com/2008/08/05/find-replace-across-multiple-file s-in-linux/