alwbtc
alwbtc

Reputation: 29445

How to search for a string in files with name containing a specific string in linux?

I want to search recursively for "MY:STRING" string in files whose name contains "20121218" in them, the output should give me the file name and location. Search should look in files under sub-directories as well.

Upvotes: 0

Views: 824

Answers (3)

SudoSURoot
SudoSURoot

Reputation: 443

I prefer to use:

find . -type f ( -name '20121218' ) -print0 | xargs -0 grep --color -n MYSTRING

...which will show you the file path, name, and line number (with color) everywhere MYSTRING is located within files containing 20121218.

EX. from my Android Kernel source:

find . -type f ( -name 'config' ) -print0 | xargs -0 grep --color -n MSM8974

returns many, but here is a few:

./arch/arm/mach-msm/Kconfig:254:config ARCH_MSM8974

./arch/arm/mach-msm/Kconfig:255: bool "MSM8974"

./arch/arm/configs/g2-kddi-perf_defconfig:41:CONFIG_ARCH_MSM8974=y

./arch/arm/configs/g2-kddi-perf_defconfig:44:CONFIG_MACH_MSM8974_G2_KDDI=y

./arch/arm/configs/lgl22_defconfig:314:CONFIG_ARCH_MSM8974=y

./arch/arm/configs/g2-open_com-perf_defconfig:503:CONFIG_MACH_MSM8974_A1=y

./arch/arm/configs/g2-open_com-perf_defconfig:516:CONFIG_SND_SOC_MSM8974=y

Upvotes: 1

Chris Seymour
Chris Seymour

Reputation: 85765

Use find and grep:

find . -type f -name '*20121218*' -exec fgrep -l "MY:STRING" {} \;

Explanation:

find the command find.

. start looking in the current directory.

-type f only interested in files.

-name filename match against '*20121218*'

-exec execute the following command on the files found.

fgrep fixed string grep.

-l print only filenames that contain a match.

{} the list of matched files from find command.

\; delimiter.

Edit:

$ find . -type f -mtime -18

Upvotes: 3

dogbane
dogbane

Reputation: 274532

Use recursive grep as shown below. There is no need for find.

grep -Flr --include="*20121218*" "MY:STRING" /path/to/dir

Since, you are searching for a fixed string instead of a regex, use the -F option to speed it up.

Upvotes: 3

Related Questions