Bash Script is super slow

后端 未结 2 1569
深忆病人
深忆病人 2021-01-06 22:30

I\'m updating an old script to parse ARP data and get useful information out of it. We added a new router and while I can pull the ARP data out of the router it\'s in a new

2条回答
  •  -上瘾入骨i
    2021-01-06 23:21

    1. While read loops are slow.
    2. Subshells in a loop are slow.
    3. >> (open(f, 'a')) calls in a loop are slow.

    You could speed this up and remain in pure bash, just by losing #2 and #3:

    #!/usr/bin/env bash
    
    while read -a line; do
        case "${#line[@]}" in
            6) printf '%s %s %s\n' "${line[1]}" "${line[3]}" "${line[5]}";;
            4) printf '%s %s %s\n' "${line[0]}" "${line[2]}" "${line[3]}";;
        esac
    done < zTempMonth >> zTempMonth.tmp
    

    But if there are more than a few lines, this will still be slower than pure awk. Consider an awk script as simple as this:

    BEGIN {
        print "Parsing zTempMonth"
    }   
    
    NF == 6 {
        print $2 " " $4 " " $6
    }   
    
    NF == 4 {
        print $1 " " $3 " " $4
    }   
    

    You could execute it like this:

    awk -f thatAwkScript zTempMonth >> zTempMonth.tmp
    

    to get the same append approach as your current script.

提交回复
热议问题