referencing in cmd string

K

Kali K E

Hi,

I wanted to grep a file for a pattern. The pattern is a dynamic one
stored in the string "rec". I tried to do it as follows:

cmd = "grep -c rec filelist2 > grepdata"
os.system(cmd)

But I find that the system is not referencing the contents of rec
data. There is no syntax error and also the grep itself does not crib.

Please suggest what is the correct method.

Thanks
 
D

Diez B. Roggisch

I wanted to grep a file for a pattern. The pattern is a dynamic one
stored in the string "rec". I tried to do it as follows:

cmd = "grep -c rec filelist2 > grepdata"
os.system(cmd)

You have to actually insert the data in rec into the command-string - the
shell doesn't know anything about your variable rec

This should work:

cmd = "grep -c %s filelist2 > grepdata" % rec

Beware of spaces in rec - maybe you should surround the rec string in the
command by quotes.

Diez
 
T

Terry Reedy

Kali K E said:
Hi,

I wanted to grep a file for a pattern. The pattern is a dynamic one
stored in the string "rec". I tried to do it as follows:

cmd = "grep -c rec filelist2 > grepdata"
os.system(cmd)

I believe you want the value of the string named 'rec', and not 'rec'
itself, inserted in your command string. If that value does not
itself need to be quoted within the command string, then this should
work.

"grep -c %s filelist2 > grepdata" % rec

If your pattern has chars that make it necessary to be (double?)
quoted, then maybe

'grep -c "%s" filelist2 > grepdata' % rec

will work. (The command quoting rules depend on your OS and shell.)

Terry J. Reedy


is what you
 
P

Peter Otten

Terry said:
If your pattern has chars that make it necessary to be (double?)
quoted, then maybe

'grep -c "%s" filelist2 > grepdata' % rec

will work. (The command quoting rules depend on your OS and shell.)

On Unix commands.mkarg() will apply the proper quoting rules (and add a
preceeding space which does no harm).

'grep -c %s filelist2 > grepdata' % commands.mkarg(rec)

Peter
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,164
Messages
2,570,901
Members
47,440
Latest member
in3dagenonline

Latest Threads

Top