简体   繁体   English

ksh脚本优化

[英]ksh script optimization

I have a small script that simply reads each line of a file, retrieves id field, runs utility to get the name and appends the name at the end. 我有一个小脚本,可以简单地读取文件的每一行,检索id字段,运行实用程序以获取名称并将名称附加在末尾。 The problem is the input file is huge (2GB). 问题是输入文件很大(2GB)。 Since output is same as input with a 10-30 char name appended, it is of the same order of magnitude. 由于输出与输入相同,并附加了10到30个字符的名称,因此它的数量级相同。 How can I optimize it to read large buffers, process in buffers and then write buffers to the file so the number of file accesses are minimized? 我如何优化它以读取大缓冲区,在缓冲区中进行处理,然后将缓冲区写入文件中,从而最大程度地减少文件访问次数?

#!/bin/ksh
while read line
do
    id=`echo ${line}|cut -d',' -f 3`

    NAME=$(id2name ${id} | cut -d':' -f 4)

    if [[ $? -ne 0 ]]; then
        NAME="ERROR"
        echo "Error getting name from id2name for id: ${id}"
    fi

    echo "${line},\"${NAME}\"" >> ${MYFILE}
done < ${MYFILE}.csv

Thanks 谢谢

You can speed things up considerably by eliminating the two calls to cut in each iteration of the loop. 您可以通过消除循环的每次迭代中的两个cut调用来显着加快处理速度。 It also might be faster to move the redirection to your output file to the end of the loop. 将重定向到输出文件的位置移到循环末尾可能也更快。 Since you don't show an example of an input line, or what id2name consists of (it's possible it's a bottleneck) or what its output looks like, I can only offer this approximation: 由于您没有显示输入行的示例,也不显示id2name组成(可能是瓶颈)或其输出是什么样,所以我只能提供以下近似值:

#!/bin/ksh
while IFS=, read -r field1 field2 id remainder   # use appropriate var names
do
    line=$field1,$field2,$id,$remainder
    # warning - reused variables
    IFS=: read -r field1 field2 field3 NAME remainder <<< $(id2name "$id")
    if [[ $? -ne 0 ]]; then
        NAME="ERROR"
        # if you want this message to go to stderr instead of being included in the output file include the >&2 as I've done here
        echo "Error getting name from id2name for id: ${id}" >&2  
    fi
    echo "${line},\"${NAME}\""
done < "${MYFILE}.csv" > "${MYFILE}"

The OS will do the buffering for you. 操作系统将为您进行缓冲。

Edit: 编辑:

If your version of ksh doesn't have <<< , try this: 如果您的ksh版本没有<<< ,请尝试以下操作:

    id2name "$id" | IFS=: read -r field1 field2 field3 NAME remainder

(If you were using Bash, this wouldn't work.) (如果您使用的是Bash,则无法使用。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM