Home > Back-end >  Bash Script using Grep
Bash Script using Grep

Time:11-16

I am writing a bash script to search for a pattern in a file using grep. I don't understand why grep doesn't return something. When I run the same command in cmd it works (in cmd instead of $a, I put the text directly). echo $a works correctly, that is, the variable is not null. I tried putting the $a between double quotes and single quotes, but nothing works. Does anyone have any idea what is going on?

input="file.txt"
while IFS= read -r line
do
    a=$(cut -d "," -f1 <<< $line)
    b=$(cut -d "," -f2 <<< $line)
  if [ $a==$b ]
  then
    echo "$a"
    index=$(grep -n "$a" another_file.txt| cut -d ":" -f1)
    echo "$index"
  fi
done < "$input"

CodePudding user response:

The immediate problem is that [ $a==$b ] doesn't do what you want, but it doesn't explain your problem. The proper syntax is

[ "$a" = "$b" ]

with spaces on both sides of the operator, a single = (Bash tolerates two, but it's not properly portable) and proper quoting.

However, that doesn't explain why your code isn't working. Without access to your input data, it is not really possible to see what is supposed to happen.

Tangentially, you want to use IFS to split the line into fields.

while IFS="," read -r a b _; do
   ...

The proper solution in this case is to refactor your script into an Awk script, which is both more compact, more readable, and faster.

awk -F , 'NR==FNR { if ($1 == $2) keyword = keyword (keyword ? "|" : "") $1; next }
    $0 ~ keyword { print FNR }' file.txt another_file.txt

If you need the output in a particular order, or the matched keyword to be printed as part of the output, this requires some refactoring, but using Awk a single time over the input file is basically always a win (though if the file is small, you don't really care).

CodePudding user response:

I found the problem. Variables a and b contained \r at the end. I used bash -x ./script.sh to figure it out.

Thanks anyway

  • Related