bash - Shell - Pipe to multiple commands in a file -
i want run 2 commands on piped-in input , want print (to stdout) output of both.
each command combination of grep, sed , awk.
both these commands must reside in single .sh file.
sample commands:
cat mult_comm.sh sed 's/world/boy/g'|grep boy ; grep world # input cat input.log hello world # command has work cat input.log | bash mult_comm.sh expected output
hello boy hello world actual output
hello boy i tried using tee
cat mult_comm.sh tee >(sed 's/world/boy/g'|grep boy) | grep world but gives
hello world i can modify .sh file want piped command can't changed. ideas?
this similar os x / linux: pipe 2 processes? , pipe output 2 different commands, can't figure out how use named pipes inside script.
when execute
tee >(some_command) bash creates subshell run some_command. subshell's stdin assigned reading half of pipe. bash leaves name of pipe on command line, tee pump input pipe. subshell's stdout , stderr left unchanged, still same tee's.
so, when execute
tee >(some_command) | some_other_command now, bash first creates process run tee, , assigns stdout writing half of pipe, , process run some_other_command, stdin assigned reading half of same pipe. creates process run some_command, above, assigning stdin reading half of pipe, , leaving stdout , stderr unchanged. however, stdout has been redirected some_other_command, , that's some_command inherits.
in actual example,
tee >(sed 's/world/boy/g'|grep boy) | grep world we end with:
--> sed 's/world/boy/g' --> grep boy -- / \ input --> tee --< \ \ \ ----------------------------------------------> grep world in 1 of questions linked in op, there (non-accepted correct) answer f. hauri, i've adapted here:
echo hello world | ((tee /dev/fd/5 | grep world >/dev/fd/4) \ 5>&1 | sed 's/world/boy/' | grep boy) 4>&1 it takes little practice read bashisms above. important part that
( commands ) 5>&1 creates subshell (( )) , gives subshell fd numbered 5, copied stdout (5>&1). inside subshell, /dev/fd/5 refers fd. within subshell, possible redirect stdout, happen after stdout copied fd5.
Comments
Post a Comment