使用python改进bash脚本

时间:2013-01-29 19:45:54

标签: python linux bash shell unix

如何减少以下的冗余?也就是说,有没有办法将两个几乎相同的语句合并为一个?

FULFILLMENT="/Users/david/Desktop/pds" # "/Volumes/FulfilmentArray/"
ARCH1="/Users/david/Desktop/etc" # "/Volumes/Arch_01/"

FILE="/tmp/files.txt"

# find all the paths and print them to a file
sudo find $FULFILLMENT -ls | python -c '
import sys
for line in sys.stdin:
    r = line.strip("\n").split(None, 10)
    fn = r.pop()
    print ",".join(r) + ",\"" + fn.replace("\"", "\"\"") + "\""
' > $FILE &&

sudo find $ARCH1 -ls | python -c '
import sys
for line in sys.stdin:
    r = line.strip("\n").split(None, 10)
    fn = r.pop()
    print ",".join(r) + ",\"" + fn.replace("\"", "\"\"") + "\""
' >> $FILE

3 个答案:

答案 0 :(得分:4)

查找可以在一个命令中查看多个目录:

FULFILLMENT="/Users/david/Desktop/pds" # "/Volumes/FulfilmentArray/"
ARCH1="/Users/david/Desktop/etc" # "/Volumes/Arch_01/"

FILE="/tmp/files.txt"

# find all the paths and print them to a file
sudo find "$FULFILLMENT" "$ARCH1" -ls | python -c '
import sys
for line in sys.stdin:
    r = line.strip("\n").split(None, 10)
    fn = r.pop()
    print ",".join(r) + ",\"" + fn.replace("\"", "\"\"") + "\""
' > $FILE 

答案 1 :(得分:1)

你可以这样做:

cmd='
import sys
for line in sys.stdin:
    r = line.strip("\n").split(None, 10)
    fn = r.pop()
    print ",".join(r) + ",\"" + fn.replace("\"", "\"\"") + "\""
'
sudo find $FULFILLMENT -ls | python -c "$cmd" >> $FILE
sudo find $ARCH1 -ls | python -c "$cmd" >> $FILE

答案 2 :(得分:1)

虽然以下内容略有不同,但我怀疑你会更满意:

FULFILLMENT=/Users/david/Desktop/pds
ARCH1=/Users/david/Desktop/etc
exec > /tmp/files.txt

find $FULFILLMENT $ARCH1 -exec stat -c '%i,%b,%A,%h,%U,%G,%y,%n' {} \;

日期的格式不同,如果您没有使用POSIXLY_CORRECT调用statfind可能会报告不同的块大小。这不会尝试转义文件名中的引号,也不会将文件名放在引号中,因为您显然不担心可能包含逗号的文件名,因此我们可以假设输出可以作为csv可靠地解析而不用担心引号。