Find the answer to your Linux question:
Results 1 to 3 of 3
Hi, I have a file: 979798707 787862348 766428634 I want to see if all the records in the file are present in the contents of the files of a particular ...
Enjoy an ad free experience by logging in. Not a member yet? Register.
  1. #1
    Just Joined!
    Join Date
    Sep 2010
    Posts
    12

    How to tell if grep didn't return anything


    Hi,

    I have a file:

    979798707
    787862348
    766428634

    I want to see if all the records in the file are present in the contents of the files of a particular directory.

    Basically I want to say if grep doesn't return anything, then report.

    For example in /tmp dir I have 4 files and flast 2 values (787862348 and 766428634) are present in the files of /tmp dir, but first one (979798707) is not. I want to echo that in a reporting file.

    something like:

    while read line
    do
    # if ! grep -rl $line /tmp
    echo $line >> are_not_present
    done < "myFile"


    How do I achieve " if ! grep -rl $line /tmp"? That is, if the line is found by grep, then grep will print the output, but if grep does'nt find it, it will print nothing. How can I check if grep didn't find it (i.e. printed nothing)?

    Thanks,

  2. #2
    Linux Newbie
    Join Date
    Mar 2009
    Posts
    228
    Check the return status ($?)

    When grep finds something return status is 0
    When grep doesn't find something return status is 1

  3. #3
    Linux User stokes's Avatar
    Join Date
    Oct 2004
    Location
    UK
    Posts
    274
    how about something like:

    Code:
    for line in $(cat file); do
     for file in $(ls /tmp); do
      if [ -z "(grep $line /tmp/$file)" ]; then
       echo "I couldn't find $line in /tmp/$file"; 
      else
       echo "I found $line in /tmp/$file";
      fi
     done
    done
    this is checking for the existance of each line in "file" in every file in /tmp/ and reporting a yes or no. If you don't want to see the "I couldn't find the file", you could change the -z clause to "! -z".

    Code:
    for line in $(cat file); do
     for file in $(ls /tmp); do
      if [ ! -z "(grep $line /tmp/$file)" ]; then
       echo "I found $line in /tmp/$file";
      fi
     done
    done
    Edit: I should have explained. testing using -z is testing for a blank string. Check out "man test", which explains all the different clauses you can use in if statements.
    Last edited by stokes; 03-15-2011 at 09:30 PM.
    Registered Linux user #389109
    My Semi-Linux Blog

  4. $spacer_open
    $spacer_close

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •