MacOS Bash-Script: while read p and echo

27 Views Asked by At

I have the following input-file (p) ($inputFile)

PING 8.8.8.8 (8.8.8.8): 56 data bytes
11:36:27.996138 64 bytes from 8.8.8.8: icmp_seq=1 ttl=109 time=48.066 ms
11:36:28.991554 64 bytes from 8.8.8.8: icmp_seq=2 ttl=109 time=39.374 ms
Request timeout for icmp_seq 3
11:36:31.000927 64 bytes from 8.8.8.8: icmp_seq=4 ttl=109 time=41.830 ms

--- 8.8.8.8 ping statistics ---
4 packets transmitted, 3 packets received, 25.0% packet loss
round-trip min/avg/max/stddev = 30.542/40.064/54.798/6.720 ms

I want another file ($outputFile), based on the input-file, which should have this structure:

  • write 0 if the line contains the word "bytes"
  • write 1 if the line contains the word "timeout"

this should give me this

0
0
1
0

I use this bash function-fragment to achieve this

while read p; do
  if echo "$p" | grep 'bytes from'; then
    echo 0
  elif echo "$p" | grep 'timeout'; then
    echo 1
  fi
done <$inputFile >>$outputFile

What I really get in the $outputFile is

11:36:27.996138 64 bytes from 8.8.8.8: icmp_seq=1 ttl=109 time=48.066 ms
0
11:36:28.991554 64 bytes from 8.8.8.8: icmp_seq=2 ttl=109 time=39.374 ms
0
Request timeout for icmp_seq 3
1
11:36:31.000927 64 bytes from 8.8.8.8: icmp_seq=4 ttl=109 time=41.830 ms
0

How do I get rid of the original lines in the output-file ($outputFile)?

0

There are 0 best solutions below