I think of xargs
as the map function of the UNIX shell. What is the filter
function?
EDIT: it looks like I'll have to be a bit more explicit.
Let's say I have to hand a program which accepts a single string as a parameter and returns with an exit code of 0 or 1. This program will act as a predicate over the strings that it accepts.
For example, I might decide to interpret the string parameter as a filepath, and define the predicate to be "does this file exist". In this case, the program could be test -f
, which, given a string, exits with 0 if the file exists, and 1 otherwise.
I also have to hand a stream of strings. For example, I might have a file ~/paths
containing
/etc/apache2/apache2.conf
/foo/bar/baz
/etc/hosts
Now, I want to create a new file, ~/existing_paths
, containing only those paths that exist on my filesystem. In my case, that would be
/etc/apache2/apache2.conf
/etc/hosts
I want to do this by reading in the ~/paths
file, filtering those lines by the predicate test -f
, and writing the output to ~/existing_paths
. By analogy with xargs
, this would look like:
cat ~/paths | xfilter test -f > ~/existing_paths
It is the hypothesized program xfilter
that I am looking for:
xfilter COMMAND [ARG]...
Which, for each line L
of its standard input, will call COMMAND [ARG]... L
, and if the exit code is 0, it prints L
, else it prints nothing.
To be clear, I am not looking for:
- a way to filter a list of filepaths by existence. That was a specific example.
- how to write such a program. I can do that.
I am looking for either:
- a pre-existing implementation, like
xargs
, or - a clear explanation of why this doesn't exist