I am using grep within a script to obtain a list of filenames of the files that contain a certain string. The basic instruction would be this one within a do loop:

if grep -q "$str" Inputs/inp$n; then
    echo inp$n >> file_list.txt  

And something like this to get the lines themselves for verification purposes:

grep "$str" Files/inp$n >> lines.txt

What I would like to do is prevent some false positives from showing up in the output when looking for certain strings. I would like to get the lines containing "abc#", where "#" is a number (multiple digits possible), but I do not want the specific word "abcde" from appearing when I am searching for the string "abc". Note that "abc#" and "abcde" are not present in the same line within these files.

Is there any way to tell grep to ignore the lines that contain "abcde" among those containing "abc"?

  • 1
    Try grep 'abc[0-9]' "Inputs/inp$n" – John1024 Apr 2 '19 at 17:49
  • That works fine, thanks. I actually used "$str[0-9]" as the searched string. – ZZR Apr 2 '19 at 21:35
$ grep -l 'abc[0-9]' Inputs/inp*

The -l switch will list files which have a match. Giving a glob of files to search rather than iterating will likely be faster than iterating over a shell for loop.

  • That works, it just provides the whole path of the file. I basically adapted my solution based on your feedback to search for "$str[0-9]" and it works as intended. Thanks. Running it for all inp* would be a good option in most cases. I actually get the numbers for the inp$n files to search from a list in another file. – ZZR Apr 2 '19 at 21:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.