这是我起草的python脚本......
#!/opt/app/python/bin/python
# Convert ls output to clean csv Paolo Villaflores 2015-03-16
#
# Sample usage: ls -l | ls2csv.py
#
# Features:
# accepts -d argument to change dates to yyyy-mm-dd_hhmm format
# input is via stdin
# separate file/directory field
# handle -dils type input (find -ls) versus -l
# handle space in filename, by applying quotes around filename
# handle date - format into something excel can handle correctly, whether it is from current year or not.
# adds a header
# handle symlinks - type l
import sys
from datetime import datetime
b0=True
def is_f(s):
if s == '-':
return 'f'
return s
for line in sys.stdin:
if len(line) < 40:
continue
if b0:
b1=line[0] in ['-', 'd', 'c', 'l'] # c is for devices e.g. /devices/pseudo/pts@0:5, l is for symbolic link
b0=False
if b1: # true when shorter ls -l style 8/9 columns. 9 for symlink
cols=7
print "d,perms,#links,owner,group,size,modtime,name,symlink"
else:
cols=9
print "inode,bsize,d,perms,#links,owner,group,size,modtime,name,symlink"
r = line.strip("\n").split(None, cols+1)
if len(r) < cols+1:
continue
if r[cols-7][0] == 'c':
continue # ignore c records: devices
fn = r.pop()
if b1:
c = ''
else:
c = ",".join(r[0:2]) + ","
z = 0
z = r[cols].find(':')
if z < 0:
d = r[cols - 1] + "/" + r[cols - 2] + "/" + r[cols]
else:
n = str(datetime.now() )
d = ''
# handle the case where the timestamp has no year field
tm=datetime.strptime(r[cols-2]+ " " + r[cols-1]+ " " + n[:4] +" " + r[cols], "%b %d %Y %H:%M")
if (tm-datetime.now()).days > 0:
d = r[cols - 1] + "/" + r[cols - 2] + "/" + str((datetime.now().year-1)) + " " + r[cols]
tm=datetime.strptime(r[cols-2]+ " " + r[cols-1]+ " " + str(int(n[:4])-1) +" " + r[cols], "%b %d %Y %H:%M")
else:
d = r[cols - 1] + "/" + r[cols - 2] + "/" + " ".join([n[:4], r[cols] ] )
if len(sys.argv) > 1 and sys.argv[1] == '-d':
d=tm.strftime("%Y-%m-%d_%H%M")
y = fn.find(">")
symlink=''
if y > 0:
symlink = ',\"' + fn[y+2:] + '"'
fn = fn[:y-2]
if fn.find( " ") <0:
if fn.find('"') <0:
fn2=fn
else:
fn2="'" + fn + "'"
else:
fn2="'" + fn + "'"
print c+ is_f(r[cols-7][0]) + ",\"" + r[cols-7][1:] + "\"," + ",".join(
r[cols-6:cols-2]) + "," + d + "," + fn2 + symlink