0

Suppose, I have a string "Transferred 6.7828 MB in 244.434 seconds (28.4151 KB/sec)". I want to get 244.434 seconds out of this and this is just an example, these values can change. Basically I need to know the time taken (in seconds from this string). I am implementing this in Linux. How to do via grep?

This input will come from a log file abc.log.

Yogesh
  • 47
  • 1
  • 10
  • 2
    With awk: `awk '{print $5}' <<< 'Transferred 6.7828 MB in 244.434 seconds (28.4151 KB/sec)'` – Cyrus Aug 31 '18 at 03:23
  • 1
    Please avoid *"Give me the codez"* questions. Instead show the script you are working on and state where the problem is. Also see [How much research effort is expected of Stack Overflow users?](https://meta.stackoverflow.com/q/261592/608639) – jww Aug 31 '18 at 05:44

3 Answers3

2

If you can be sure about the order of your output, then

echo "Transferred 6.7828 MB in 244.434 seconds (28.4151 KB/sec)" | cut -d' ' -f5

Output

244.434

At least is easier than sed.

1

You could try with this grep:

$ grep -oE "[0-9\.]* seconds" file
244.434 seconds

where file:

Transferred 6.7828 MB in 244.434 seconds (28.4151 KB/sec)

EDIT (suggested by @Cyrus)

Assuming that you just want the amount of seconds:

$ grep -oP "[0-9.]+(?= seconds)" file
244.434
Joaquin
  • 2,013
  • 3
  • 14
  • 26
0

You'll need grep and sed for this:

grep "Transferred .* in .* seconds" abc.log | sed -e 's/^.*Transferred .* in \([0-9][0-9]*[.][0-9][0-9]*\) seconds .*/\1/'

Output:

244.434
dbush
  • 205,898
  • 23
  • 218
  • 273
  • Your capture group could be anything, better `sed 's/^.*in[ ]\([0-9][0-9]*[.][0-9][0-9]*\).*$/\1/'` (but I like your fuller use of `"Transferred..."`) – David C. Rankin Aug 31 '18 at 03:22
  • @DavidC.Rankin Good point. Updated. – dbush Aug 31 '18 at 03:25
  • After you added the initial `grep`, then it would have probably been good enough either way (depending on what else could be in the log), but when needing to match numbers, it's always good to be explicit. – David C. Rankin Aug 31 '18 at 03:26
  • Realistically there should be no need for `sed` as `grep` has the `-o` option to output only the matching pattern. – trs Aug 31 '18 at 03:41
  • @trs, there should similarly be no need for `grep` as `sed` can do the same search with a regex in `1addr`. There's no "one right way" to do most things. – ghoti Aug 31 '18 at 04:38
  • @ghoti ... Well let's just rephrase it to "there is no need to pipe output to two programs". The point which you missed is that this answer suggests using both which is not necessary. – trs Sep 03 '18 at 09:29
  • @trs, didn't miss it at all, that's exactly what I was saying. Perhaps you missed the fact that I was suggesting that *either* tool would work. – ghoti Sep 03 '18 at 17:45