linux - Get the nth column out of a text document (Python 3) -
i'm trying write code allow linux mint users install recommended packages software installed on machine. list of packages installed, run following in bash:
grep 'install' /var/log/dpkg.log
this returns this:
2015-09-24 19:39:01 install libportsmf0:amd64 <none> 0.1~svn20101010-4 2015-09-24 19:39:02 install libsbsms10:amd64 <none> 2.0.2-1 2015-09-24 19:39:03 install libsoxr0:amd64 <none> 0.1.1-1 2015-09-24 19:39:04 install libwxbase3.0-0:amd64 <none> 3.0.2-1+b1 2015-09-24 19:39:05 install libwxgtk3.0-0:amd64 <none> 3.0.2-1+b1 2015-09-24 19:39:07 install libvamp-hostsdk3:amd64 <none> 1:2.5-dmo6 2015-09-24 19:39:08 install audacity-data:all <none> 2.0.6-2 2015-09-24 19:39:10 install audacity:amd64 <none> 2.0.6-2 2015-09-25 11:47:36 install hardinfo:amd64 <none> 0.5.1-1.4 2015-09-25 12:14:35 install libstdc++6:i386 <none> 4.9.2-10 2015-09-25 12:14:36 install libudev1:i386 <none> 215+12+betsy 2015-09-25 12:14:37 install libtinfo5:i386 <none> 5.9+20140913-1+b1 2015-09-25 12:14:38 install libbsd0:i386 <none> 0.7.0-2 2015-09-25 12:14:39 install libedit2:i386 <none> 3.1-20140620-2 2015-09-25 12:14:40 install nvidia-installer-cleanup:amd64 <none> 20141201+1
what need able grab fourth column of each line says package name. libportsmf0:amd64, libsbsms10:amd64... point, i've tried piping output of grep 'install' file, opening file python 3, , using loop grab third column, such that
import os def recommends(): os.system("grep 'install' /var/log/dpkg.log >> ~/irfiles.txt") file1 = '~/irfiles.txt'
but haven't been able figure out how set loop yet. thanks!
why not doing directly via bash?
using cut
# $ cat /var/log/dpkg.log | grep 'install' | cut -f4 -d" "
the field parameter -f<number>
can different, have status
inbetween, me it's -f5
. -d
parameter says it's separated spaces not tabs.
exclude unwanted output via grep -v
and if want exclude <none>
in output, can extend command inverted grep (grep -v
) this:
# $ cat /var/log/dpkg.log | grep 'install' | cut -f4 -d" " | grep -v '<none>'
it's easy pipe more grep -v
commands after whole command more excluded (which done 1 regular expression, way more easy understand).
removing duplicates @ end sort
, uniq
if have duplicates in output, can remove them using sort
, uniq
.
# $ cat /var/log/dpkg.log | grep 'install' | cut -f4 -d" " | grep -v '<none>' | sort | uniq
python
if want python, can this:
# statement not necessary, recommended. open("/var/log/dpkg.log") logfile: line in logfile: # covers 'installed', 'half-installed', … # deeper processing can use re module, it's not necessary if "install" in line.split()[3]: # or [4] # code here print(line)
Comments
Post a Comment