Search code examples
bashmacoscut

How can I make cut take less time to process?


I have a text file with a whole bunch of lines (1000 exactly) and they all have 4 bits of text, seperated by a ;.

Here is the for loop I'm using, to go through each line:

while IFS= read -r line; do
    let liner++
    if [[ liner -eq "1" ]]; then
        continue
    fi

    name=$(echo "${line}" | cut -d';' -f1)
    fullname=$(echo "${line}" | cut -d';' -f2)
    id=$(echo "${line}" | cut -d';' -f3)
    test=$(echo "${line}" | cut -d';' -f4)

    echo "${GREEN}$(($liner-1))) ${name} ${ORANGE}v${test} ${RED}(${id})${NC}"
    stuff+=("${fullname}")
done < list.txt

It takes about 5 seconds before it finishes running and I believe it's from all those cut (name, fullname, id, test) variables. What would be the best solution to speed this up?


Solution

  • Awk undoubtedly provides a better solution, but if you don't want to learn Awk right now, you could speed your function up a lot by just using read to split the lines into fields:

    liner=0
    stuff=()
    while IFS=\; read -r name fullname id test; do
        echo "$GREEN$((++liner))) $name ${ORANGE}v$test $RED($id)$NC"
        stuff+=("$fullname")
    done < <(tail -n+2 1000num.txt)