bashwhile-loopprefixprefix-tree

Optimize prefix checks of lines while iterating through file


I'm writing a script in the form

while read LINE 
do
    [[ $LINE =~ ^headertag1 ]] && function1 && continue
    [[ $LINE =~ ^headertag2 ]] && function2 && continue
    ...
done < filename

As the number of tags increase, I will be doing too many checks per line. I can trying sorting the common tags higher up, but I don't think it solves the fundamental issue. I'm not a software engineer. Are there programming concepts/methods that can improve this situation?


Solution

  • Not sure here, but if you look for tidying up your code and feel bored by adding these if guards repetitively, then maybe this idea will help:

    #!/bin/bash
    
    tags[tag1]="some regex1"
    tags[tag2]="some regex2"
    tags[tag3]="some regex3"
    
    function action() {
      echo "perl -pe '${tags[$tag]} other-file.txt'"
    }
    
    while read LINE; do
      for tag in "${!tags[@]}"; do
        [[ $LINE =~ ^$tag ]] && action "${tags[$tag]}"
      done
    done < filename
    

    Not sure if the OP is asking something like this.