Discuss Output ls|awk to dict question in the Python Programming forum on Dev Shed. Output ls|awk to dict question Python Programming forum discussing coding techniques, tips and tricks, and Zope related information. Python was designed from the ground up to be a completely object-oriented programming language.
Posts: 1
Time spent in forums: 48 m 13 sec
Reputation 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..
Posts: 404
Time spent in forums: 1 Week 5 h 6 m 48 sec
Reputation Power: 65
Quote:
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.
__________________
My armada: openSUSE 12.3 (home desktop, laptop, work desktop), Ubuntu 12.04 LTS (mini laptop), Debian GNU/Linux 7.0 (server), Mythbuntu 12.04 LTS (HTPC), Bodhi Linux 2.0 & Windows 7 Ultimate (test desktop), FreeBSD 9.1 (test server)