【问题标题】:Issue with program check if the number is divisible by 2 with no remainder BASH程序检查问题是否可以被 2 整除且没有余数 BASH
【发布时间】:2018-06-29 02:56:18
【问题描述】:

我试图编写一个程序来查看计数是否可以被 2 整除而没有余数 这是我的程序

count=$((count+0))

while read line; do

if [ $count%2==0 ]; then
    printf "%x\n" "$line" >> file2.txt
else
    printf "%x\n" "$line" >> file1.txt
fi

count=$((count+1))
done < merge.bmp

这个程序每次进入真实状态都不起作用

【问题讨论】:

  • 即使在这里也尝试使用算术 cmd:if (( count % 2 == 0 )).
  • if (( count % 2 == 0 )) 内置测试[ 不支持%。即使是这样,== 周围也应该有空格。
  • count=$((count+0)) 是干什么用的?
  • 初始化变量
  • @cdarke 我试过了,如果你写了它仍然不起作用。

标签: bash division


【解决方案1】:

在 shell 中,[ 命令根据您提供的多少个参数 执行不同的操作。见https://www.gnu.org/software/bash/manual/bashref.html#index-test

有了这个:

[ $count%2==0 ]

你给[一个单个参数(不包括尾随的]),在这种情况下,如果参数不为空,则退出状态为成功(即“真” )。这相当于[ -n "${count}%2==0" ]

你想要

if [ "$(( $count % 2 ))" -eq 0 ]; then

或者,如果您使用的是 bash

if (( count % 2 == 0 )); then

【讨论】:

    【解决方案2】:

    一些更“异国情调”的方式来做到这一点:

    count=0
    files=(file1 file2 file3)
    num=${#files[@]}
    
    while IFS= read -r line; do
        printf '%s\n' "$line" >> "${files[count++ % num]}"
    done < input_file
    

    这会将第一行放入file1,将第二行放入file2,将第三行放入file3,将第四行放入file1等等。

    【讨论】:

      【解决方案3】:

      awk 来救援!

      你想要做的是单线

      $ seq 10 | awk '{print > (NR%2?"file1":"file2")}'
      
      ==> file1 <==
      1
      3
      5
      7
      9
      
      ==> file2 <==
      2
      4
      6
      8
      10
      

      【讨论】:

        【解决方案4】:

        试试

        count=$((count+0))
        
        while read line; do
        
        if [ $(($count % 2)) == 0 ]; then
            printf "%x\n" "$line" >> file2.txt
        else
            printf "%x\n" "$line" >> file1.txt
        fi
        
        count=$((count+1))
        done < merge.bmp
        

        您还必须在 mod 运算符周围使用 $(( ))。

        How to use mod operator in bash?

        这将打印“偶数”:

        count=2;
        if [ $(($count % 2)) == 0 ]; then
            printf "even number";
        else
            printf "odd number";
        fi
        

        这将打印“奇数”:

        count=3;
        if [ $(($count % 2)) == 0 ]; then
            printf "even number";
        else
            printf "odd number";
        fi
        

        【讨论】:

        • [ ... ] 内部,== 运算符用于string 相等。您需要 -eq 来实现数值相等。
        猜你喜欢
        • 1970-01-01
        • 2015-03-06
        • 2020-10-23
        • 2015-01-26
        • 1970-01-01
        • 2011-02-18
        • 1970-01-01
        相关资源
        最近更新 更多