0

I have a very simple awk command running within subprocess call; it does exactly what I want in terms of printing the data within $1

import subprocess
subprocess.call("awk '{print $1}' textfile.txt")

However, what I'd like to do is work with the data contained within $1. Is there a way that I can pass the result back in to Python?

Or would it be better to do this directly within Python? If so, this is where I'm not finding what I'm looking for in terms of printing text file columns in as simple a way as awk. Any pointers would be much appreciated, thank you.

oguz ismail
  • 1
  • 16
  • 47
  • 69
Darren
  • 31
  • 5
  • 2
    This is completely trivial to do natively if you know the basics of Awk and Python. `with open('textfile.txt') as lines: for line in lines: print(line.split()[0])` (assuming your lines have more than one field; otherwise you'll need to separately get rid of the newline). And obviously, do something else than `print()` the field if that's what you want. – tripleee Sep 16 '21 at 13:16
  • Thanks for this, I took out the [0] and it prints the contents of the text file as ['-77.84000', '-0.06355'] ['-77.76000', '+0.0000'] However, I'd just like the first column of it (the part with -77x values. – Darren Sep 16 '21 at 13:27
  • Duh, that's what the `[0]` did. – tripleee Sep 16 '21 at 13:28
  • That gives me the error IndexError: list index out of range – Darren Sep 16 '21 at 13:31
  • 1
    Then you have some empty lines. Just skip those. Awk is slightly more lenient in this situation, and simply prints an empty line. Is that what you want? `if not line.rstrip('\n'): print('') else: print(line.split()[0])` – tripleee Sep 16 '21 at 13:35
  • Perfect, that got it ... Yeah there was a couple of empty lines in there. My checks on the output work exactly how I'd expect them to as well. Thank you for your help. – Darren Sep 16 '21 at 13:46

0 Answers0