Pol dePaor Pol dePaor - 2 months ago 6
Linux Question

Check if an array element is in a file

I am writing a bash script to check if an array element is in a file.

For example:

I have an array of errors

errors=("1234" "5678" "9999")


I have a file that contains patterns of strings

123400 452612 9999A0 1010EB


I am looking to loop over the file that contains the errors and check to see if any of the array elements matches any string pattern in the file. If it does then give me back the exact array pattern it matched in the file for further processing.

Any ideas on how I can do this?

Answer

The script goes like this,

#/bin/bash
errors=("1234" "5678" "9999")

for error in "${errors[@]}"
do
     grep -o "$error" file
done

For a sample file,

$ cat file
123400 452612 9999A0 1010EB

The script produces an output

$ ./script.sh
1234
9999

meaning the above two keys from the array have matched in the file. The -o flag in grep is to identify only the matching parts from the array. An excerpt from the man grep page.

-o, --only-matching
         Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line.
Comments