1

I have a script which is checking a key in one file against a key in another to see if it exists in both. However in the script the grep never returns anything has been found but on the command line it does.

#!/bin/bash
# First arg is the csv file of repo keys separated by line and in
# this manner 'customername,REPOKEY'
# Second arg is the log file to search through

log_file=$2
csv_file=$1
while read line;
do 
    customer=`echo "$line" | cut -d ',' -f 1`
    repo_key=`echo "$line" | cut -d ',' -f 2`
    if [ `grep "$repo_key" $log_file` ]; then
        echo "1"
    else
        echo "0"
    fi
done < $csv_file

The CSV file is formatted as follows:

customername,REPOKEY

and the log file is as follows:

REPOKEY

REPOKEY

REPOKEY

etc

I call the script by doing ./script csvfile.csv logfile.txt

2 Answers 2

2

Rather then checking output of grep command use grep -q to check its return status:

if grep -q "$repo_key" "$log_file"; then
    echo "1"
else
    echo "0"
fi

Also your script can be simplified to:

log_file=$2
csv_file=$1
while IFS=, read -r customer repo_key; do
    if grep -q "$repo_key" "$log_file"; then
        echo "1"
    else
        echo "0"
    fi
done < "$csv_file"
Sign up to request clarification or add additional context in comments.

2 Comments

Hmm, changing this still didn't change my original result, it's like the grep isn't working inside the script?
Just before grep insert echo "[$repo_key]" and tell me what value do you get
0

use the exit status of the grep command to print 1 or 0

repo_key=`echo "$line" | cut -d ',' -f 2`

grep -q "$repo_key" $log_file

if [ $? -eq 1  ]; then
        echo "1"
    else
        echo "0"
    fi

-q supresses the output so that no output is printed

$? is the exit status of grep command 1 on successfull match and 0 on unsuccessfull

you can have a much simpler version as

grep -q "$repo_key" $log_file
echo $?

which will produce the same output

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.