linux - How to filter lines with a filter chain -
linux - How to filter lines with a filter chain -
suppose have text file, list.txt
, this:
# category 1 foobar # category 2 dummy1 dummy2 dummy3 # category 3 foobar.dummy foobar.dummy
and have bash script, say, list.sh
, extract lines list.txt
. script takes 1 or more patterns filter text file grep. conceptually, commandline:
cat list.txt | grep filter1 | grep fitler1 | ... | grep filtern
however, problem number of filters varies, have utilize loop filtering. loop, hoping below work.
filters=$* filter in ${filters[@]}; result=`ad_hoc_show $result | grep $filter` done ad_hoc_show $result # should maintain original line construction
for example, below desired output.
$ list.sh foobar foobar foobar.dummy foobar.dummy $ list.sh dummy \d dummy1 dummy2 dummy3
so, advice on how implement ad_hoc_show
function?
if grep
supports -p
can utilize function:
filt() { re=$(printf "(?=.*?%s)" "$@") grep -p "$re" list.txt } filt 'dummy' '\d' dummy1 dummy2 dummy3 filt 'foobar' foobar foobar.dummy foobar.dummy
update: in case grep -p
not available can utilize awk
:
filt() { re=$(printf "/%s/&&" "$@"); awk "${re:0: -2}" list.txt; } filt 'dummy' '[0-9]' dummy1 dummy2 dummy3 filt 'foobar' foobar foobar.dummy foobar.dummy
linux bash
Comments
Post a Comment