简体   繁体   中英

Match List of Numbers in For Loop in Bash

I have a script that loops over a curl command, which pulls in data from an API.

LIST_OF_ID=$(curl -s -X POST -d "username=$USER&password=$PASS&action=action" http://link.to/api.php)

for PHONE_NUMBER in $(echo $LIST_OF_ID | tr '_' ' ' | awk '{print $2}');
do
  $VOIP_ID = $(echo $LIST_OF_ID | tr '_' ' ' | awk '{print $1}')
done

I also have a variable of 16 numbers in the range of " 447856321455 "

NUMBERS=$(cat << EOF
441111111111
441111111112
441111111113
... etc
)

The output on the API call is:

652364_441111111112

As you may notice I have taken the output and cut it into 2 parts and put it in a variable.

What I need is to match the 6 digit code from the output where the number in the output, matches with the number in the variable.

I've attempted it using if statements but I can't work my head around the correct way of doing it.

Any help would be appreciated.

Thank you.

I would do it using join rather than a loop in bash. Like this:

curl -s -X POST -d "$PARAMS" "$URL" | sort \
  | join -t _ -2 2 -o 2.1 <(sort numbers.txt) -

What this does is take the sorted output from curl and join it with the sorted contents of numbers.txt (you could use $NUMBERS too), using _ as the separator, using column 2 of file 2 which is - meaning stdin (from curl). Then output field 2.1 which is the six-digit ID.

Read why-is-using-a-shell-loop-to-process-text-considered-bad-practice and then do something like this:

curl ... |
awk -v numbers="$NUMBERS" -F'_' '
    BEGIN { split(numbers,tmp,/[[:space:]]+/); for (i in tmp) nums[tmp[i]] }
    $2 in nums
'

but to be honest I cant really tell what it is you are trying to do as the numbers in your sample input don't seem to match each other (what does in the range of "447856321455" mean and how does it relate to $NUMBERS containing 441111111111 through 441111111113 and how does any of that relate to match the 6 digit code ) and the expected output is missing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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