Python Forum
loop in system command fails
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
loop in system command fails
#1
Create a function called filter_passwd. The fucntion must take the following
arguments:
  - A string, representing the path to a file using the /etc/passwd format (PWD)
  - A string, representing the prefix that the PWD entries will be filtered by (P)

The function must:
  1. Extract the username and UID entries from the givem PWD file
  2. Find the entries, where the username starts witht the prefix P
  3. Create/rewrite a file called 'results.txt' in the current working directory
    that contains the matching usernames and corresponding UIDs, one per line,
    delimeted by whitespace
  4. When inspected, return the following help string:
    Filter out the enries in the given PWD database that match the prefix P

Example:

If the input file (pwd.txt) contains:
    root:x:0:0:root:/root:/bin/bash
    daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
    bin:x:2:2:bin:/bin:/usr/sbin/nologin
    sys:x:3:3:sys:/dev:/usr/sbin/nologin
    sync:x:4:65534:sync:/bin:/bin/sync
    games:x:5:60:games:/usr/games:/usr/sbin/nologin
    man:x:6:12:man:/var/cache/man:/usr/sbin/nologin
    lp:x:7:7:lp:/var/spool/lpd:/usr/sbin/nologin
    mail:x:8:8:mail:/var/mail:/usr/sbin/nologin
    news:x:9:9:news:/var/spool/news:/usr/sbin/nologin

then calling
   filter_passwd('pwd.txt', 'sy')
should result in an output file results.txt containing:
   sys 3
   sync 4

calling
   filter_passwd('pwd.txt', 'r')
should result in an output file results.txt containing:
   root 0
"""

import os
def filter_passwd(*args):
    v1 = args[0]
    v2 = args[1]
    """cmd = 'grep -i \'%s\' \'%s\' | awk -F \":\" \'{print $1\" \"$3}\'' %(v2,v1)"""
    cmd = 'for line in `cat \'%s\'` ; do echo $line | awk -F \":\" \'{print $1\":\"$3}\';done' %(v1)
    os.system(cmd)

a = 'pwd.txt'
b = 'r'
filter_passwd(a,b)
The commented cmd line works fine for first example not the second;
The uncommented cmd line fails now, my intention is the extend the same command with grep -i v2  so that it works for example 2 as well...

yes... It is working with this line....
cmd = 'cat \'%s\' | awk -F \":\" \'{print $1\" \"$3}\' | grep -i \'%s\'' %(v1,v2)
Reply
#2
If this is homework, shouldn't you be using Python to do the filtering and file creation, not system commands?
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  While Loop; Can Else Point Back To Initial Input Command? RodNintendeaux 9 6,259 Oct-04-2017, 05:39 AM
Last Post: gruntfutuk

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020