Home > database >  Look for ocurrences of items in files in bash
Look for ocurrences of items in files in bash

Time:05-06

I have a bash script as follows. It basically loads the contents from a text file into a variable, then reads each line from that variable and tries to find matches of a pattern containing that item in the files under a certain folder, and finally generates a list with the items with matches.

#!/usr/bin/env bash

set -e

var_with_items=$(<"/path/to/file")
matches=""
while IFS= read -r item; do
  echo "- ${item}"
  pattern="foo/bar/${item}/"
  uses=$(grep -r "/some/path" -e "${pattern}" | wc -l)
  if [[ "${uses}" != "0" ]]; then
    matches ="${item}\n";
  fi
done < <(printf "%s\n" "$var_with_items")

The problem I'm facing is that it only checks the first line from the variable (the first item) and I don't know what the problem is because it doesn't throw any error. However, if I comment the line uses=$(grep -r "/some/path" -e "${pattern}" | wc -l), it correctly prints every line from $var_with_items, so I guess the problem is in that line, but if I execute it manually (with proper item substitution) it works.

UPDATE: In my original question I didn't add set -e at the top of the script, which makes it exit as soon as a command exits with non-zero status. That being said, as grep exits with 0 when matches are detected, and 1 otherwise, it was making the script to exit as soon as it process the first item without matches.

CodePudding user response:

grep command with option -o returns every matched pattern in a line.

Therefore suggesting:

  grep -r -o "/some/path" -e "${pattern}" | wc -l

Or:

  uses=$(grep -r -o "/some/path" -e "${pattern}" | wc -l)
 

CodePudding user response:

In my original question I didn't add set -e at the top of the script, which makes it exit as soon as a command exits with non-zero status. That being said, as grep exits with 0 when matches are detected, and 1 otherwise, it was making the script to exit as soon as it process the first item without matches.

  • Related