Which tool should I use to extract data from string?

As a quite new Linux user I never (really) used tools such as sed and awk (or any others) to parse text. I want to extract from

Speed : 1624.127424 Kib/s in 9.410000 seconds

the time value in second, just before the seconds word ,

Which tool should I look into for this ?

Answers


There are a number of tools you could use, but awk will do fine:

echo "Speed : 1624.127424 Kib/s in 9.410000 seconds" | awk '{print $6}'

or (if your data is in a file):

awk '{print $6}' data.txt

gives you

9.410000

Explanation:

This assumes that the relative position of the value you are interested in on the line will stay the same (and in this case be the 6th white-space separated field), adjust accordingly.

awk splits the input line up into fields based on white-space. The field you are interested in is the 6th field, so you are printing that with $6.

Alternatively, you could have also used awk '{print $(NF-1)}' to print the next-to-last field on the line (NF is an awk variable that knows the number of fields on a given line). This offers a bit more flexibility as it would work with an length line (ie number of fields) as long as the field you were interested in was next-to-last).

--

cut would be another tool that would work too:

echo "Speed : 1624.127424 Kib/s in 9.410000 seconds" | cut -d' ' -f 6

in this case, the line is split based on the delimiter of space (as specified by -d) and again, we are interested in the 6th field (-f 6).

There are other ways too, but these two seem straight forward and came to mind first.


Need Your Help

file.png isn't precompiled

ruby-on-rails-3.1 sass asset-pipeline imageurl

I thought I had the assets pipeline figured out, but not any more.

PHP+AJAX: How to make toggle for sorting data?

php jquery mysql ajax toggle

I have a very simple page, where is the list of users from database. On this page is a table containing these information, with name, surname, age, city.