with grep:
How to find all files containing specific text (string) on Linux - Stack Overflow
Do the following:
grep -rnw '/path/to/somewhere/' -e 'pattern'
-r
or-R
is recursive, ==> see comment below: -r is dfs-lazy, -R is greedy-n
is line number, and-w
stands for match the whole word.-l
(lower-case L) can be added to just give the file name of matching files.-e
is the pattern used during the search
Along with these, --exclude
, --include
, --exclude-dir
flags could be used for efficient searching:
- This will only search through those files which have .c or .h extensions:
grep --include=\*.{c,h} -rnw '/path/to/somewhere/' -e "pattern"
- This will exclude searching all the files ending with .o extension:
grep --exclude=\*.o -rnw '/path/to/somewhere/' -e "pattern"
- For directories it's possible to exclude one or more directories using the
--exclude-dir
parameter. For example, this will exclude the dirs dir1/, dir2/ and all of them matching *.dst/:
grep --exclude-dir={dir1,dir2,*.dst} -rnw '/path/to/somewhere/' -e "pattern"
This works very well for me, to achieve almost the same purpose like yours.
For more options, see man grep.
-
use --exclude. like "grep -rnw --exclude=*.o 'directory' -e "pattern"
– rakib_
it's worth noting: it seems ther
option is lazy (traverses depth-first, than stops after the first directory), whileR
is greedy (will traverse the entire tree correctly). - Note(especially for newbies): The quotation marks in the above command are important.
-
– madD7
follow up: edit all found files with 'xargs' and 'sed'
from: How to replace a string in multiple files in linux command line - Stack Overflow
simple soln.
cd /path/to/your/folder
sed -i 's/foo/bar/g' *
Occurrences of "foo" will be replaced with "bar".
On BSD systems like macOS, you need to provide a backup extension like -i '.bak'
or else "risk corruption or partial content" per the manpage.
cd /path/to/your/folder
sed -i '.bak' 's/foo/bar/g' *
a much better soln.
@kev's answer is good, but only affects files in the immediate directory.The example below uses grep to recursively find files. It works for me everytime.
grep -rli 'old-word' * | xargs -i@ sed -i 's/old-word/new-word/g' @
Command breakdown
grep -r: --recursive, recursively read all files under each directory.
grep -l: --print-with-matches, prints the name of each file that has a match, instead of printing matching lines.
grep -i: --ignore-case.
xargs: transform the STDIN to arguments, follow this answer.
xargs -i@ ~command contains @~: a placeholder for the argument to be used in a specific position in the ~command~, the @ sign is a placeholder which could replaced by any string.
sed -i: edit files in place, without backups.
sed s/regexp/replacement/: substitute string matching regexp with replacement.
sed s/regexp/replacement/g: global, make the substitution for each match instead of only the first match.