In a generic shell script, I would like to use shell pattern matching to filter the lines of a text file.
I have a list of file names in files.txt:
file1.txt
file2.sh
file3.png
And I have a list of patterns in patterns.txt:
other_file.txt
file2.*
If I would have regular expressions in patterns.txt, I could do this:
$ grep -v -f patterns.txt files.txt
But I would like to use shell globbing patterns. I found the C function fnmatch but no shell/unix command to use it.
OK, this is going to be really unperformant, as POSIX sh does not even have arrays (which I would have used for caching the patterns):
If you don’t need the positional arguments (
$1
,$2
, …) you can abuse those for pattern caching though:Be careful about whitespace there though: we set
IFS
to a literal newline character and nothing else, i.e.IFS='
Enter'
.I’ve tested this with your dataset plus a few additions (like a
a b*
pattern, to test whitespace behaviour), and it seems to work for me according to the spec in the OP.