1

I have a data set (e.g., a file) that looks like this:

4.048   5.9392765
4.051   5.9392765
4.068   5.9392765
4.293   5.9392765
4.3 "A random string"
4.331   5.9392765
4.429   6.0137865
4.609   6.0303125
4.662   6.0303125
5.626   6.1261205
5.815   6.1261205
6.347   6.1261205
6.543   6.1261205
6.7 "A random string"
7.420   6.1611095
7.526   6.2542085
7.541   6.2698285
7.556   6.2698285
7.928   6.2698285

I want to extract groups of three lines (rows) where the second field of the middle row is a string rather than a number.  For example, for the above input, I'd like to get the following output:

4.293   5.9392765
4.3 "A random string"
4.331   5.9392765
------------------------
6.543   6.1261205
6.7 "A random string"
7.420   6.1611095

How can I do this?

  • I found your question hard to understand.  If I misunderstood it, please re-edit it to fix it. – G-Man Says 'Reinstate Monica' Apr 25 '18 at 17:36
  • @G-Man: Thank you for your response and your edit. It absolutely looks more comprehensible now! – RJF Apr 25 '18 at 17:38
  • Yeah, (1) “dataframe” is uncommon terminology, (2) I felt that “upper and lower rows” needed clarification, and (3) a computer can subtract 4607111701851759477 from 4607111701951759477 in less time than it takes a person to type a key. But people have trouble looking at long strings of digits and seeing the difference quickly. It’s better to give examples using small numbers and short strings. – G-Man Says 'Reinstate Monica' Apr 25 '18 at 17:47
0

grep solution:

grep -C1 -E '^[0-9]+\.[0-9]+[[:space:]]+[^0-9[:space:]]+' file
  • -C NUM - print NUM lines of output context
  • -E - extended regexp
  • [^0-9[:space:]]+ - match any character except whitespace(s) [:space:] or digit [0-9]

The output:

51174.29300 2265.9392765
51174.3 "A random string"
51174.33100 2265.9392765
--
51176.54300 2266.1261205
51176.7 "A random string"
51177.42000 2266.1611095
  • Thank you for your thorough explanation, this is really helpful! – RJF Apr 25 '18 at 17:21
1

A simpler answer:

grep -C1 '"' file

which finds the lines containing a quote character (") and displays them, with one line before and after.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.