axnet
axnet

Reputation: 5790

How to tokenise string and call a function on each token in bash?

I have a text file with comma delimiter like following

for example str_data.txt

aaa,111,bbb
ccc,222,ddd
eee,333,fff

I have a bash function to validate each token (i.e. if each token is following some rule or not based on that function will echo true or false. (can leave it like [[ XYZ == "$1"]] also, instead of returning echo) )

for example

function validate_token {
  local _rule = XYZ
  if [[ XYZ == "$1" ]]; then
    echo "true"
  else
    echo "false"
  fi
}

I want to write a bash script (one-liner or multi-line) to validate all these tokens separately (i.e. validate_token "aaa" then validate_token "111") and finally answer "true" or "false" based on ANDing of each token's results.

Upvotes: 2

Views: 405

Answers (2)

tshiono
tshiono

Reputation: 22032

Would yo please try the following:

validate_token() {
    local rule="???"    # matches a three-chraracter string
    if [[ $1 == $rule ]]; then
        echo 1
    else
        echo 0
    fi
}

final=1                 # final result
while IFS=',' read -ra ary; do
    for i in "${ary[@]}"; do
        final=$(( final & $(validate_token "$i") ))
        # take AND with the individual test result
    done
done < "str_data.txt"

(( $final )) && echo "true" || echo "false"

I've also modified your function due to several reasons.

  • When defining a bash function, the form name() { .. } is preferred.
  • It is not recommended to start the user's variable name with an underscore. You have localized it and don't have to care about the variable name collision.
  • When evaluating the conditional expression by using == or = operator within [[ .. ]], it will be better to place the pattern or rule to the right of the operator.
  • It will be convenient to return 1 or 0 rather than true or false for further calculation.

Hope this helps.

Upvotes: 1

nullPointer
nullPointer

Reputation: 4574

You can try the below, reading line by line and storing the values into an array, then iterating the array calling the function for each value :

IFS=","
while read line
do 
   read -ra lineValues <<< "$line"
   for value in "${lineValues[@]}"
   do 
      validate_token "$value" 
   done
done < your_txt_file

Upvotes: 0

Related Questions