referencing in cmd string

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Kali K E

    referencing in cmd string

    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
  • Diez B. Roggisch

    #2
    Re: referencing in cmd string

    > I wanted to grep a file for a pattern. The pattern is a dynamic one[color=blue]
    > stored in the string "rec". I tried to do it as follows:
    >
    > cmd = "grep -c rec filelist2 > grepdata"
    > os.system(cmd)[/color]

    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

    Comment

    • Terry Reedy

      #3
      Re: referencing in cmd string


      "Kali K E" <kalike2003@net scape.net> wrote in message
      news:ab5a234a.0 309140638.e81fb [email protected] le.com...[color=blue]
      > 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)[/color]

      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


      Comment

      • Peter Otten

        #4
        Re: referencing in cmd string

        Terry Reedy wrote:
        [color=blue]
        > 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.)[/color]

        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

        Comment

        Working...