检查整数是否为数组中的元素

时间:2020-04-01 06:22:48

标签: bash comparison

我需要检查值c是否存在于整数数组中,我知道如何使用for循环和if语句来实现这一点:

@Test
public void testb3Generator() throws IOException {
    File f = new File(inputFile);

    outputFile = String.format("%s_b3-3.pdf", "123");

    try (PDDocument document = PDDocument.load(f)) {

        PDDocumentCatalog catalog = document.getDocumentCatalog();
        PDAcroForm acroForm = catalog.getAcroForm();
        int i = 0;
        for (PDField field : acroForm.getFields()) {
            i=i+1;
            if (field instanceof PDTextField) {
                PDTextField textField = (PDTextField) field;
                textField.setValue(Integer.toString(i));
            }
        }

        document.getDocumentCatalog().getAcroForm().flatten();

        document.save(new File(outputFile));
        document.close();
    }
    catch (Exception e) {

        e.printStackTrace();
    }
}

完成

但是我不想要这个,我尝试了类似的东西:

    for c in {1..100};do
        sequence=(2 4 6 8 10 12 14 16)    
        for value in "${sequence[@]}";do
           if [[ $value -eq $c ]];then  #If c exists in sequence
              flag=1
              break
           fi
    done

但是它没有给我想要的结果,我认为它仅适用于字符串数组,而不适用于整数。

我该如何处理?

2 个答案:

答案 0 :(得分:0)

将我的评论转换为答案,以便将来的访问者容易找到解决方案。

您可以使用以下grep + printf解决方案:

grep -qFx "$c" <(printf '%s\n' "${sequence[@]}") && echo "found" || echo "nope"

答案 1 :(得分:0)

此方法[[ ${sequence[*]} =~ $c ]]的问题在于,如果$c为1,则它将与所有实例匹配为1。尝试这种方法,使序列成为这样的正则表达式

re=${sequence[*]}
re=${re// /|}
$ echo $re
2|4|6|8|10|12|14|16

测试

c=1
$ [[ $c =~ $re ]] && echo ok || echo fail
fail

c=11
$ [[ $c =~ $re ]] && echo ok || echo fail
fail

c=12
$ [[ $c =~ $re ]] && echo ok || echo fail
ok
相关问题