#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2013
    Posts
    1
    Rep Power
    0

    Output ls|awk to dict question


    Hello,

    I'm hoping someone might be able/willing to point me in the right direction to combat a small challenge Iím facing.
    I'm pretty new to Python and already went thoroughly through "Learning Python (4th.ed)" and though this forum, but still not able to achieve the following:

    I'm trying to create a dictionary in python3 based on the output of an awk'd ls command: ls -l | grep - | awk {'print $9","$5'}

    The output from os.system("ls -l /bin | grep - | awk {'print $9\"=\" $5\",\"'}") seems to me to be the first step, but how to convert this to a dict is where i'm stuck..


    Thanks for any pointers you might have!

    Regards,
    Mike.
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2007
    Location
    Joensuu, Finland
    Posts
    439
    Rep Power
    67
    Originally Posted by mik3nl
    I'm trying to create a dictionary in python3 based on the output of an awk'd ls command: ls -l | grep - | awk {'print $9","$5'}
    If Iím getting you right, the ďgrep -Ē part is there to get rid of the header line, $9 is the filename and $5 the fileís size. (BTW, you are relying on a specific formatting of lsís output. If ls happens to be aliased or the localisation in use differs, for example, the field numbers might change.)

    I think the smart way is to use Python all the way through:

    Code:
    import os
    fileinfo = {}
    for filename in os.listdir('.'):
        fileinfo[filename] = os.stat(filename).st_size
    Later on you could replace the '.' parameter with the contents of sys.argv, for instance.

    Comments on this post

    • b49P23TIvg agrees : Great answer. mik3nl script fails when file name contains space.
    My armada: openSUSE 13.2 (home desktop, work desktop), openSUSE 13.1 (home laptop), Debian GNU/Linux 7.7.0 (mini laptop), Ubuntu 14.04 LTS (server), Android 4.2.1 (tablet), Windows 7 Ultimate (testbed)

IMN logo majestic logo threadwatch logo seochat tools logo