user5418726
user5418726

Reputation:

GREP values from a column in txt file

I have a txt file with 1200 entries in this way (iPerf output by the way)

1  [  4]  0.0- 1.0 sec  10.6 MBytes  89.1 Mbits/sec
2  [  4]  1.0- 2.0 sec  13.5 MBytes   113 Mbits/sec
3  [  4]  2.0- 3.0 sec  9.50 MBytes  79.7 Mbits/sec
4  [  4]  3.0- 4.0 sec  9.00 MBytes  75.5 Mbits/sec

How can I get ONLY the second values expressed in Mbits/sec using grep ?

Output example:

89.1
113
79.7
75.5

Upvotes: 0

Views: 836

Answers (2)

karakfa
karakfa

Reputation: 67467

if your data is fixed length format you can always use cut

cut -c38-41 data

if you know that the values are 4 chars wide.

Upvotes: 0

zedfoxus
zedfoxus

Reputation: 37039

awk '{print $9}' your-file.txt 

will do it for you. For example:

$ cat ~/test.txt
1  [  4]  0.0- 1.0 sec  10.6 MBytes  89.1 Mbits/sec
2  [  4]  1.0- 2.0 sec  13.5 MBytes   113 Mbits/sec
3  [  4]  2.0- 3.0 sec  9.50 MBytes  79.7 Mbits/sec
4  [  4]  3.0- 4.0 sec  9.00 MBytes  75.5 Mbits/sec

$ awk '{print $9}' ~/test.txt
89.1
113
79.7
75.5

Another way to tackle this is:

 awk -F 'MBytes' '{print $2}' test.txt | awk -F 'Mbits' '{print $1}' | tr -d " "

In the above method we are:

  • Splitting each line by MBytes.
  • That gives us 2 parts: $1 is everything before MBytes. $2 is everything after MBytes
  • We choose everything after MBytes and split it further by Mbits
  • That gives us two parts again and we choose everything before Mbits
  • If there is white space before and after the numbers, we use tr to remove white space

So we get

$ cat test.txt
1  [  4]  0.0- 1.0 sec  10.6 MBytes  89.1 Mbits/sec
2  [  4]  1.0- 2.0 sec  13.5 MBytes   113 Mbits/sec
3  [  4]  2.0- 3.0 sec  9.50   MBytes  79.7 Mbits/sec
4  [  4]  3.0- 4.0 sec  9.00 MBytes    75.5 Mbits/sec

awk -F 'MBytes' '{print $2}' test.txt | awk -F 'Mbits' '{print $1}' | tr -d " "

Result:
89.1
113
79.7
75.5

Upvotes: 3

Related Questions