简体   繁体   中英

How to use a command output as input for grep in shell script

I have a shell script which derive lots of data from multiple logs files each day. Furthermore I created another script which will do more processing on that data and grep a string and give a count with grep -c .

I have tried below mentioned way but second script not taking input from first output

./myfirstsctipt | ./mysecondscript

How my second script will use first script output as input for grep script?

I have tried using firstscript as argument for second like below but did not work.

./mysecondscript $(./myfirstsctipt )

Even its not working with cat as first command my file content is like that

TIME+2019-10-25 00:09:11.184
TIME+2019-10-25 00:12:11.184
TIME+2019-10-25 00:13:11.184
TIME+2019-10-25 00:16:11.184
TIME+2019-10-25 00:18:11.184
TIME+2019-10-25 00:20:11.184
TIME+2019-10-25 00:22:11.184
TIME+2019-10-25 00:26:11.184
TIME+2019-10-25 00:27:11.184
TIME+2019-10-25 00:28:11.184
TIME+2019-10-25 00:30:11.184

and mysecondscript is

#!/bin/bash
#set -vx

for hour in `seq -w 0 23`
do
  for min in `seq -w 0 59`
  do
    a=`grep -c "$hour:$min:"  `
    echo "$hour:$min   $a"
  done
done

I am trying like below.

cat test2 | ./mysecondscript.sh

You can't read standard input more than once. The first iteration consumes all the input in the first invocation of grep -c and subsequent iterations will simply draw the proverbial blank.

You could solve this with a temporary file (the idiom is t=$(mktemp -t foo.XXXXXXXX) || exit; cat >"$t"; trap 'rm -f "$t"' ERR EXIT and then grep -c regex "$t" as many times as you like) but you want to avoid temporary files if you can - and anyway, in this case, a much more efficient solution is to only read the input once.

awk '{ t[substr($2, 1, 5)]++ }
  END { for(h=0; h<24; h++) {
    hh = sprintf("%02i", h);
    for(m=0; m<60; m++) {
      mm = sprintf("%02i", m);
      printf("%s:%s %i\n", hh, mm, t[hh ":" mm]) } } }'

Demo: https://ideone.com/MjyzXR

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM