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.

4
  • Have you seen stackoverflow.com/questions/6736627/… Commented Jul 18, 2011 at 19:40
  • can you give us the output, like what it is printing? Commented Jul 18, 2011 at 19:42
  • Why you're trying to use awk for that, when you can use pure Python easily? Commented Jul 18, 2011 at 19:43
  • taking a look at that link now thanks this: '/'251'/{print $2}' will print: 8472 im not sure how to do this in python alone? Commented Jul 18, 2011 at 19:45

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks you've set me on the right path for sure. Sorry about using awk, rookie mistake!
@Kilizo: You have Python. You don't need much more. You barely need the shell.
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)

Comments

0

I think what you're looking for is:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.