I have two strings. For the sake of the example they are set like this:
string1=\"test toast\"
string2=\"test test\"
What I want is to find
Another python-based answer, this one based on the os.path module's native commonprefix function
#!/bin/bash
cat mystream | python -c $'import sys, os; sys.stdout.write(os.path.commonprefix(sys.stdin.readlines()) + b\'\\n\')'
Longform, that's
import sys
import os
sys.stdout.write(
os.path.commonprefix(sys.stdin.readlines()) + b'\n'
)
/!\ Note: the entire text of the stream will be loaded into memory as python string objects before being crunched with this method
If not buffering the entire stream in memory is a requirement, we can use the communicative property and to the prefix commonality check between every input pair
$!/bin/bash
cat mystream | python -c $'import sys\nimport os\nfor line in sys.stdin:\n\tif not os.path.isfile(line.strip()):\n\t\tcontinue\n\tsys.stdout.write(line)\n') | pythoin sys.stdin:\n\tprefix=os.path.commonprefix([line] + ([prefix] if prefix else []))\nsys.stdout.write(prefix)''
Long form
import sys
import os
prefix = None
for line in sys.stdin:
prefix=os.path.commonprefix(
[line] + ([prefix] if prev else [])
)
sys.stdout.write(prefix)
Both of these methods should be binary-safe, as in they don't need input/output data to be ascii or utf-8 encoded, if you run into encoding errors, python 3 renamed sys.stdin to sys.stdin.buffer and sys.stdout to sys.stdout.buffer, which will not automatically decode/encode input/output streams on use