Skip to main content
Add explanation, use more robust test
Source Link
AdminBee
  • 23.6k
  • 25
  • 55
  • 77

Assuming you have no whitespace and no characters that are special characters of regular expressions contained in your strings in "file1".txtfile1.txt, the following awk-based approach should work:

awk 'NR==FNR{patterns[FNR]=$1} FNR<NR{if (index($0 ~ ,patterns[FNR])>0) print "true"; else print "false"}' file1.txt file2.txt

For your example, this will yield

true
true
true
true
true
false

Some explanation: We use awk to read in both files, but process them in a different way.

  • While processing file1.txt, indicated by FNR, the "per-file line counter", being equal to NR, the global line counter, we simply register all (trimmed) strings ($1, which is the first whitespace-delimited field of the line) in an awk-internal array, with the line number as index (note that these start with 1).

  • While processing file2.txt (FNR is now smaller than NR), we use the index function to look for the string patterns[FNR] in the entire input line ($0). If so, index() will return a start position larger than 0, and we print true, otherwise we print false.

Assuming you have no whitespace and no characters that are special characters of regular expressions contained in your strings in "file1".txt, the following awk-based approach should work:

awk 'NR==FNR{patterns[FNR]=$1} FNR<NR{if ($0 ~ patterns[FNR]) print "true"; else print "false"}' file1.txt file2.txt

For your example, this will yield

true
true
true
true
true
false

Assuming you have no whitespace contained in your strings in file1.txt, the following awk-based approach should work:

awk 'NR==FNR{patterns[FNR]=$1} FNR<NR{if (index($0,patterns[FNR])>0) print "true"; else print "false"}' file1.txt file2.txt

For your example, this will yield

true
true
true
true
true
false

Some explanation: We use awk to read in both files, but process them in a different way.

  • While processing file1.txt, indicated by FNR, the "per-file line counter", being equal to NR, the global line counter, we simply register all (trimmed) strings ($1, which is the first whitespace-delimited field of the line) in an awk-internal array, with the line number as index (note that these start with 1).

  • While processing file2.txt (FNR is now smaller than NR), we use the index function to look for the string patterns[FNR] in the entire input line ($0). If so, index() will return a start position larger than 0, and we print true, otherwise we print false.

Source Link
AdminBee
  • 23.6k
  • 25
  • 55
  • 77

Assuming you have no whitespace and no characters that are special characters of regular expressions contained in your strings in "file1".txt, the following awk-based approach should work:

awk 'NR==FNR{patterns[FNR]=$1} FNR<NR{if ($0 ~ patterns[FNR]) print "true"; else print "false"}' file1.txt file2.txt

For your example, this will yield

true
true
true
true
true
false