user2023
user2023

Reputation: 478

Skip the filenames whch do not have contents while doing a for loop

I'm grepping a string in files under a directory as i don't know in which file the string_something exits thus I'm listing all the files and doing grep on then to identify, this works however in the echo statement i only want the the Files which have the string value found rest skip the filename in the output.

for i in `ls -Xl| awk '{print $NF}'`;do echo "-- $i --"; grep string "$i";done

Output

-- file1 --
-- file2 --
-- file3 --
-- file4 --
-- file5 --
-- file6 --
some output   ( all the output matching to the `string` matched)
-- file7 --
-- file8 --
-- file9 --
some output   ( all the output matching to the `string` matched)

Desired output..

-- file6 --
some output
-- file9 --
some output

Upvotes: 0

Views: 71

Answers (4)

David C. Rankin
David C. Rankin

Reputation: 84579

The proper way to simply get the names of the files containing "string_something" is:

grep -l -d skip -F 'string_something' *

If you insist on wrapping the filename in "-- name --", then you can loop over the results of grep and format the output as desired, e.g.

for i in $(grep -l -d skip -F 'string_something' *); do
    printf -- "-- %s --\n%s\n" "$i" 'string_something'
done

Look things over and let me know if you have further questions.

Upvotes: 1

Jetchisel
Jetchisel

Reputation: 7801

You could try the -q option if you're just interested in the files which has the word string in it.

for files in *; do
  [[ -f $files ]] || continue          ##: Don't grep directories.
  if grep -q string -- "$files"; then  ##: Don't output anything if string is found.
    echo "$files"                      ##: Print the files which has string in it.
  fi 
done

This might do what you want though.

for files in *; do
  [[ -f $files ]] || continue                ##: Don't grep directories.
  if found=$(grep string -- "$files"); then  ##: Save successful match in the variable found 
    printf '%s\n %s\n' --"$files"-- "$found"   ##: Print the desired output.
  fi 
done

Upvotes: 2

Ivan
Ivan

Reputation: 7287

Grep can do it alone

grep -ril 'string' /path/to/search

From grep's help

$ grep --help
...
-r, --recursive           like --directories=recurse
-i, --ignore-case         ignore case distinctions
-l, --files-with-matches  print only names of FILEs with selected lines
...

Upvotes: 2

d0niek
d0niek

Reputation: 238

try:

grep -rin path/to/dir -e string_to_search

Upvotes: 1

Related Questions