简体   繁体   English

Bash中For循环中的数字匹配列表

[英]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. 我有一个循环执行curl命令的脚本,该命令从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 " 我也有16个数字的变量,范围为“ 447856321455

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

The output on the API call is: API调用的输出为:

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. 我需要匹配输出中的6位数字,其中输出中的数字与变量中的数字匹配。

I've attempted it using if statements but I can't work my head around the correct way of doing it. 我已经尝试过使用if语句,但是我无法正确地做到这一点。

Any help would be appreciated. 任何帮助,将不胜感激。

Thank you. 谢谢。

I would do it using join rather than a loop in bash. 我会使用join而不是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). 这样做是采取排序的输出curl并与排序内容加入它numbers.txt (你可以使用$NUMBERS也行),使用_作为分隔符,使用柱2文件2这是-这意味着标准输入(从卷曲)。 Then output field 2.1 which is the six-digit ID. 然后输出字段2.1 ,即六位ID。

Read why-is-using-a-shell-loop-to-process-text-considered-bad-practice and then do something like this: 阅读为什么使用一个shell循环来处理文本考虑的不良做法 ,然后执行以下操作:

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. 但老实说,由于样本输入中的数字似乎彼此不匹配,我真的无法说出您正在尝试做什么in the range of "447856321455"是什么,以及它与$ NUMBERS的关系如何)包含441111111111441111111113 ,以及其中的任何一个与match the 6 digit code如何),并且缺少预期的输出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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