1

I have a file filled by rows of text, I'm interested about a group of these, every line starts with the same word, in each line there are two numbers i have to elaborate later, and they are always in the same position, for example:

Round trip time was 49.9721 milliseconds in repetition 5 tcp_ping received 128 bytes back

I was thinking about trying to use grep to grab the rows wanted into a new file, and then put the content of this new file into an array, to easily access it during the elaboration, but this isn't working, any tips?

#!/bin/bash
InputFile="../data/N.dat"
grep "Round" ../data/tcp_16.out > "$InputFile"
IFS=' ' read -a array <<< "$InputFile"
5
  • <<< "$InputFile" is a here string; you need regular redirection (< "$InputFile"). Commented May 19, 2016 at 19:19
  • Or just read -a array < <(grep ...), with no temporary file at all. Commented May 19, 2016 at 19:19
  • though right now, you're reading only the first line into the array; if you want an array element per line, that's IFS=$'\n' read -r -d '' -a array Commented May 19, 2016 at 19:19
  • anyhow, can you come up with a better description for your question? "Taking input from a file" is hugely vague. "Reading lines from command output into an array" would be better, if that's actually what you want. "Extracting numeric values from grep output", even better. Commented May 19, 2016 at 19:21
  • ...for a comprehensive general introduction to reading input in bash, btw, see BashFAQ #1: mywiki.wooledge.org/BashFAQ/001 Commented May 19, 2016 at 19:30

1 Answer 1

1

If they're all you care about, you can read only the numbers in.

I'd also strongly suggest extracting the values you're going to be analyzing into arrays, like so, rather than storing the full lines as strings:

ms_time_arr=( )    # array: map repetitions to ms_time
bytes_arr=( )      # array: map repetitions to bytes

while read -r ms_time repetition bytes_back _; do
  # log to stderr to show that we read the data
  echo "At $ms_time ms, repetition $repetition, got $bytes_back back" >&2
  ms_time_arr[$repetition]=$ms_time
  bytes_arr[$repetition]=$bytes_back
done < <(grep -e 'Round' <../data/N.dat | tr -d '[[:alpha:]]')

# more logging, to show that array contents survive the loop
declare -p ms_time_arr bytes_arr

This works by using tr to remove all alpha characters, leaving only numbers, punctuation and whitespace.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.