3

most of the solutions out there call awk from python. But i want to do it the other way round. I have a python script that extracts information from a file. However said filename is referenced in a column of the awk script.

How do i pass python the argument "%s20s", filename and get the input from the standard output? i want to add the output as several columns more.

thanks for your examples

Cheers

1
  • 5
    What have you tried so far? What is your awk script? Help us help you! The more detail the better! Commented May 3, 2011 at 13:39

2 Answers 2

3

The awk variable FILENAME gives the name of the current file being processed (or '-' if stdin). However, this is not available in the BEGIN block, but you can use ARGV[1] instead (assuming you are only passing one filename):

#!/bin/awk -f

BEGIN {
    cmd = "./myscript.py '\"%s20s\"' " ARGV[1]
    print cmd
    cmd  | getline var       
    print var
}

The python script (py3) I used for testing was:

#!/usr/bin/python

import sys
print(sys.argv)

So I get the following output:

/home/user1> runit.awk afile
./myscript.py "%s20s" afile
['./myscript.py', '"%s20s"', 'afile']
Sign up to request clarification or add additional context in comments.

Comments

3

You can call external commands using the system function. Does that solve your problem?

$ awk 'BEGIN { system("echo something") }'
something

But that only provides the return code. If you need to capture stdin you can do this:

$ awk 'BEGIN { "echo something" | getline; print "output: "$0 }'
output: something

Getline works line-by-line so if you want multiple lines:

$ awk 'BEGIN { while ("cat multi_line_file" | getline) { print "output: "$0 } }'
output: line 1
output: line 2
output: line 3

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.