bash return only first line that contains match for each line in a file code example

Example 1: bash return only first line that contains match for each line in a file

# Basic syntax
while IFS= read -r LINE;
do
    grep -m number_matches "$LINE" target_file >> output_file
done < reference_file

# Where
#	- the reference_file is the file of lines you want to search for
#	- the target_file is the file you want to search
#	- number_matches is the number of matching lines to return from the
#		target file (set to 1 for returning first match)
#	- IFS= preserves leading and trailing white space in LINE
#	- -r prevents read from treating \ as a special character
#	- >> appends matching lines to output_file rather than overwriting it

Example 2: bash return only first line that contains match

# Basic syntax:
grep -m 1 "pattern" input_file.txt
# Where -m is the maximum number of matching lines to return, i.e. stop
#	reading the file after m matches
# Note, this is more efficient than piping to head because there you
#	always read the whole file even if you're only looking for m matches

Tags:

Misc Example