0

Im still new to python. I have a text file with a list of numbers, and each number has two 'attributes' along with it:

250 121 6000.654
251 8472 650.15614
252 581  84.2

i want to search for the 1st column and return the 2nd and 3rd columns as separate variables so i can use them later.

cmd = """ cat new.txt | nawk '/'251'/{print $2}' """
os.system(cmd)

This works in that it prints the $2 column, but i want to assign this output to a variable, something like this (however this returns the number of errors AFAIK):

cmdOutput =  os.system(cmd)

also i would like to change the nawk'd value based on a variable, something like this:

cmd = """ cat new.txt | nawk '/'$input'/{print $2}' """

If anyone can help, thanks.

Kilizo
  • 3,192
  • 4
  • 19
  • 20

3 Answers3

5

Don't use cat and nawk. Please.

Just use Python

import sys
target= raw_input( 'target: ' ) # or target= sys.argv[1]
with open('new.txt','r') as source:
    for columns in ( raw.strip().split() for raw in source ):
        if column[0] == target: print column[1]

No cat. No nawk.

S.Lott
  • 384,516
  • 81
  • 508
  • 779
2

First of all, to format the cmd string, use

input = '251'
cmd = """ cat new.txt | nawk '/'{input}'/{{print $2}}' """.format(input=input)

But really, you don't need an external command at all.

input = '251'
with open('new.txt', 'r') as f:
    for line in file:
        lst = line.split()
        if lst[0] == input:
            column2, column3 = int(lst[1]), float(lst[2])
            break
    else: # the input wasn't found
        column2, column3 = None, None
print(column2, column3)
agf
  • 171,228
  • 44
  • 289
  • 238
0

I think what you're looking for is:

subprocess.Popen(["cat", "new.txt","|","nawk","'/'$input/{print $2}'"], stdout=subprocess.PIPE).stdout
ryan
  • 1